Recently in doing small procedures many pictures uploaded to the Java background, Java background is written with SpringBoot. Is also stepped on a lot of pits, today to take you step by step to achieve the small program end of the picture upload.

First look at the effect realization diagram

The applet side upload successful callback

In fact, these two screenshots can be seen that we have successfully uploaded the picture, and returned the accessible picture URL to the front end of the small program. Without further ado, just look at the code.

One, small program side code

1. WXML layout file

  • Applets can only upload one image at a time
  • If the for loop is used to upload the request, parallel uploading will occur, and a certain image will be missed in parallel uploading
  • I adopted a serial approach, executing one upload request for each image, and uploading the second image after a successful response, and so on. The complete code is posted below to give you
Page({
  data: {
    img_arr: [],
    formdata: ' '}, // Click the publish buttonformSubmit{this.uploadFile(0)}, // uploadFile:function(index) {var that = this // If all images have been uploaded, no further execution is performedif (index >= that.data.img_arr.length) {
      return
    }
    wx.uploadFile({
      url: 'http://localhost:8080/upload/picture'FilePath: that.data.img_arr[index], name:'content',
      header: {
        "Content-Type": "multipart/form-data".'accept': 'application/json'.'Authorization': 'okgoodit'}, formData: ({// select * from user where user = 'user');"Programming pebbles",
        password: '2501902696'
      }),
      success: function(res) {the console. The log (` first${index+1}', res) index++ tha.uploadfile (index)}, fail(res) {console.log(' first${index+1}Upload failed ', res)}})}, // Select the image upimg:function() { var that = this; // You can change it by yourselfif (this.data.img_arr.length < 3) {
      wx.chooseImage({
        sizeType: ['original'.'compressed'], // You can specify whether the image is original or compressed. By default, both are availablesourceType: ['album'.'camera'], // You can specify whether the source is photo album or camera, and default to both success:function(res) { that.setData({ img_arr: that.data.img_arr.concat(res.tempFilePaths) }); }})}else {
      wx.showToast({
        title: 'Upload up to 3 images',
        icon: 'loading', duration: 3000 }); }}})Copy the code

The comments in the code are clear. So this is basically the end of the little program. Let’s look at the implementation of the Java background.

Second, Java background code

Let’s take a look at the background code directory, and the background code is pretty simple, just a UploadController

@RequestMapping("/picture")
    public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = "";
        request.setCharacterEncoding("utf-8"); String realPath = request.getSession().getServletContext().getrealPath ()"/uploadFile/"); File dir = new File(realPath); // Create a file directory if it does not existif(! dir.isDirectory()) { dir.mkdirs(); } try { StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; Iterator<String> Iterator = req.getFilenames (); String username = request.getParameter("username");
            String password = request.getParameter("password");
            String timedata = request.getParameter("timedata");

            while(iterator.hasNext()) { MultipartFile file = req.getFile(iterator.next()); String fileName = file.getOriginalFilename(); String uuid = uuid.randomuuid ().toString().replace()"-"."");
                String kzm = fileName.substring(fileName.lastIndexOf("."));
                String filename = uuid + kzm;
                File file1 = new File(realPath + filename);
                OutputStream out = new FileOutputStream(file1);
                out.write(file.getBytes());
                out.close();
                filePath = request.getScheme() + ": / /" +
                        request.getServerName() + ":"
                        + request.getServerPort()
                        + "/uploadFile/" + filename;
                System.out.println("Access image path :" + filePath + "====username:" + username);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return filePath;

    }
Copy the code

So let me show you the implementation steps

  • 1. Springboot provides external interfaces for small programs to access
  • 2, small program to upload a single picture and additional parameters to the background
  • 3, the background will write the picture to the local, or the picture server, and then return the corresponding picture URL to the small program end.

    As can be seen from the above figure, the Java background returned the corresponding picture URL to the front end, and you can get the user name passed by the front end of the small program. I’ll post the complete code here.

package com.img.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.UUID; @restController@requestMapping ()"/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping("/picture")
    public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filePath = "";
        request.setCharacterEncoding("utf-8"); String realPath = request.getSession().getServletContext().getrealPath ()"/uploadFile/"); File dir = new File(realPath); // Create a file directory if it does not existif(! dir.isDirectory()) { dir.mkdirs(); } try { StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; Iterator<String> Iterator = req.getFilenames (); String username = request.getParameter("username");
            String password = request.getParameter("password");
            String timedata = request.getParameter("timedata");

            while(iterator.hasNext()) { MultipartFile file = req.getFile(iterator.next()); String fileName = file.getOriginalFilename(); String uuid = uuid.randomuuid ().toString().replace()"-"."");
                String kzm = fileName.substring(fileName.lastIndexOf("."));
                String filename = uuid + kzm;
                File file1 = new File(realPath + filename);
                OutputStream out = new FileOutputStream(file1);
                out.write(file.getBytes());
                out.close();
                filePath = request.getScheme() + ": / /" +
                        request.getServerName() + ":"
                        + request.getServerPort()
                        + "/uploadFile/" + filename;
                System.out.println("Access image path :" + filePath + "====username:" + username);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        returnfilePath; }}Copy the code

I won’t give you the basics of how to create a Springboot project.

Here, our small program many picture upload even if the big work is finished, I will record the relevant video later, interested students can pay attention to the “programming small stone” public number, reply to “many picture upload”, you can obtain the source code.