1. 程式人生 > >微信小程式開發之圖片上傳+Java服務端接收 好不好使有待確認

微信小程式開發之圖片上傳+Java服務端接收 好不好使有待確認

閒言少敘直入正題存放路徑:/root/apache-tomcat-8.5.30/webapps/images/xxx.jpg

前端程式碼在網上一搜一大堆,且搜出來的結果基本上是正確的,沒啥好說的,我連程式碼都不想貼(如果有時間的話明天整理下貼在文章結尾,沒時間的話就不貼了)。但是,但是,但是,靠譜的,不用改動就能夠正常執行的Java服務端接收程式碼,幾乎沒有,沒錯,是幾乎,沒有。因為我基本上把網上能搜出來的程式碼都試了。試到第三個的時候,有點靠譜了,遺憾的是有bug。所幸改了bug後,程式碼正常執行無誤。所以現在將服務端程式碼貼在這裡,造福後人。

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(); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104

拍著胸脯保證,這程式碼你拷貝下去就能用,而且還不要求你用什麼框架(我這裡因為專案本身用了spring,我只是用了它的RequestMapping,但是上傳邏輯本身,是和spring無關的)。

解釋一下:
1.String path = request.getRealPath(“/upload”) + “/”;
這個是圖片的存放路徑,根據列印的資訊可以看到,upload目錄就建在根目錄下。
2.微信小程式上傳的圖片檔名都是wx-file.jpg,我這裡取了從前端傳過來的userId為檔案命名。userId需要放在wx.uploadFile的formData中。

撒花,搞定。
由於微信小程式上傳圖片api要求只能是HTTPS POST請求,而本地是不支援HTTPS的,所以除錯的時候頗費了周折。還好,搞定了。感謝CCAV,感謝老公,感謝自己。
晚安。

附上微信小程式的程式碼

注意設定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) {

    }
  })