1. 程式人生 > >(小程式篇:二)伺服器接收小程式圖片

(小程式篇:二)伺服器接收小程式圖片

小程式圖片上傳,在伺服器上接收小程式上傳的圖片

前面一篇介紹了本地搭建小程式測試伺服器,但是有一定侷限性:不能上傳圖片。因為小程式上傳圖片需要驗證公用ssl證書,使用一些不正規的免費證書不能完成上傳。所以我在阿里雲上申請了一個用來測試,方法:linux伺服器配置https 。當完成這些準備工作後,就可以開始檔案上傳功能的開發了。
小程式上傳檔案及其他網路訪問介面和普通網路請求是相同的,如果在請求過程中資料傳輸失敗或者有其他錯誤,處理方式和普通網路請求處理方式相同。
小程式由微信提供介面,開發需按照一定規範,沒有那麼靈活,以下是檔案上傳:

  chooseWxImage: function (
type) { var that = this; wx.chooseImage({ sizeType: ['original', 'compressed'], sourceType: [type], success: function (res) { that.setData({ tempFilePaths: res.tempFilePaths, }), that.uploadImage(res.tempFilePaths[0]) } }) }, uploadImage:
function (type) { wx.uploadFile({ url: 'https://api.**域名**.com/upload', method: "POST", filePath: type, name: 'wximage', header: { 'content-type': 'multipart/form-data' }, data: { // 直接使用file,介面會按上傳檔案處理。寫成帶引號形式“file”是錯誤的 file: type.data }
, success: function (res) { //do something }, fail: function (res) { //do something } }) }

接收工程是使用的springboot框架,以下是伺服器接收:

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(
            HttpServletRequest request,
            // 此處file和請求引數中的file對應,content-type按照 multipart/form-data格式,否則不對應
            @RequestParam("file") MultipartFile file) {
 		String str;
        File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") + "test.jpg");
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }
        // 檔案儲存路徑
        System.out.println(saveFile.getParentFile().toString());
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
            out.write(file.getBytes());
            out.flush();
            out.close();
            str = "上傳成功";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            str = "上傳失敗," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            str = "上傳失敗," + e.getMessage();
        } 
        return str;
    }

如果除錯過程中需要檢視請求頭及請求體資訊,直接使用getHeader()方法可能出現錯誤:*** has already been called for this request。解決方法可參考部落格:https://blog.csdn.net/noseew/article/details/79179892

參考資料:
https://blog.csdn.net/xxkalychen/article/details/77842638
https://www.cnblogs.com/ityouknow/p/8298344.html