Wechat applet development image upload + Java server reception

The subject of direct entry

I have searched a lot of front-end code on the Internet, and the results are basically correct. There is nothing to say. I don’t even want to post the code (if I have time, I will organize it and paste it at the end of the article tomorrow, if I don’t have time, I will not posted). But, but, but, reliable, Java server that can run normally without modification receives code, almost no, yes, almost, no. Because I basically tried all the codes I could find on the Internet. When I tried the third one, it was a bit reliable, but unfortunately there were bugs. Fortunately, after fixing the bug, the code runs normally without error. So now paste the server-side code here for the benefit of future generations.

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * Created by majl on 2017/9/1.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping("/picture")
    public void uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取文件需要上传到的路径
        String path = request.getRealPath("/upload") + "/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        logger.debug("path=" + path);

        request.setCharacterEncoding("utf-8");  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存,
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        /**
         * 原理: 它是先存到暂时存储室,然后再真正写到对应目录的硬盘上,
         * 按理来说当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
         * 然后再将其真正写到对应目录的硬盘上
         */
        factory.setRepository(dir);
        //设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                String name = item.getFieldName();
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    String value = item.getString();
                    request.setAttribute(name, value);
                    logger.debug("name=" + name + ",value=" + value);
                } else {
                    picture = item;
                }
            }

            //自定义上传图片的名字为userId.jpg
            String fileName = request.getAttribute("userId") + ".jpg";
            String destPath = path + fileName;
            logger.debug("destPath=" + destPath);

            //真正写到磁盘上
            File file = new File(destPath);
            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到(输出流)磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
        } catch (FileUploadException e1) {
            logger.error("", e1);
        } catch (Exception e) {
            logger.error("", e);
        }


        PrintWriter printWriter = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        HashMap<String, Object> res = new HashMap<String, Object>();
        res.put("success", true);
        printWriter.write(JSON.toJSONString(res));
        printWriter.flush();
    }

I promise that you can use this code after copying it, and it doesn't require you to use any framework (I use spring here because the project itself, I just use its RequestMapping, but the upload logic itself has nothing to do with spring ).

Explain:
1.String path = request.getRealPath("/upload") + "/";
This is the storage path of the picture. According to the printed information, you can see that the upload directory is built in the root directory.
2. The file names of the images uploaded by the WeChat applet are all wx-file.jpg. Here I take the userId passed from the front end as the file name. userId needs to be placed in the formData of wx.uploadFile.

Sprinkle flowers and you're done.
Since the api requirements for uploading pictures in WeChat applet can only be HTTPS POST requests, and HTTPS is not supported locally, it took a lot of troubles to debug. Okay, it's done. Thank you CCAV, thank you husband, thank yourself.
Good night.

Attach the code of the WeChat applet

Pay attention to setting the header

  wx.uploadFile({
    url: 'https://xxxxxx/upload/picture',
    filePath: filePath,//图片路径,如tempFilePaths[0]
    name: 'image',
    header : {
      "Content-Type": "multipart/form-data"
    },
    formData:
    {
      userId: 12345678 //附加信息为用户ID
    },
    success: function (res) {
      console.log(res);
    },
    fail: function (res) {
      console.log(res);
    },
    complete: function (res) {

    }
  })

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325349206&siteId=291194637