1. 程式人生 > >java接收微信小程式上傳的檔案

java接收微信小程式上傳的檔案

用微信小程式上傳檔案,微信會生成一個wx://開頭的臨時地址,很多人看到這個臨時地址直接懵逼了,檔案在哪裡啊,怎麼取檔案,其實檔案流就在請求頭裡面,需要自己去讀取.一開始我也走了很多彎路,查閱了幾篇帖子,其實都有一些坑沒有指出來.為了方便以後大家程式碼複用,我在此做一個整合.避免後人掉坑.

1.首先貼上java後端接收檔案的程式碼,我是用的springMVC,這裡需要說一下,如果你的springMVC-common.xml裡配置了檔案上傳,那就刪掉,不然取不到流.如果用servlet直接貼上程式碼是可以的

刪掉這個

<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8" />  
  
        <property name="maxUploadSize" value="20480000" />  
</bean> 

以下是java程式碼:    不管上傳圖片,視訊,音訊只需要自己程式碼裡命名字尾就可以了

	@RequestMapping("/audio")
    public void uploadAudio(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//獲取評測id
		String id = request.getParameter("assessmentID");
        //獲取檔案需要上傳到的路徑
        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") + ".mp3";
            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();
    }

小程式程式碼   (小程式檔案上傳請求要https,但是小程式開發端可以遮蔽請求,這樣就可以請求本地來測試了)

  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) {

    }
  })


以上java程式碼  小程式程式碼   引自:http://blog.csdn.net/lili625/article/details/77783300