1. 程式人生 > >微信小程式,圖片上傳在java後端接收不到圖片的問題

微信小程式,圖片上傳在java後端接收不到圖片的問題

在使用小程式的圖片上傳時,發現一直接收不到圖片,最後找到問題是Spring-mvc.xml配置檔案對圖片進行了預處理,所以導致沒有接收到。將配置檔案

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     //設定預設編碼 
        <property name="defaultEncoding" value="utf-8">

        </property>
//上傳圖片最大大小5M <property name="maxUploadSize" value="5242440"> </property> </bean>

這一段註釋,就可以正常接收圖片了

貼一下後端程式碼

    Date date1 = new Date();
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String time = format2.format(date1);
        // 獲取檔案需要上傳到的路徑
String path = request.getRealPath("upload") + "\\"; path = path.split("webapps")[0] + "upload\\"; File dir = new File(path); if (!dir.exists()) { dir.mkdir(); } System.out.println("path=" + path); request.setCharacterEncoding("utf-8"
); // 設定編碼 // 獲得磁碟檔案條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 如果沒以下兩行設定的話,上傳大的檔案會佔用很多記憶體, // 設定暫時存放的儲存室,這個儲存室可以和最終儲存檔案的目錄不同 /** * 原理: 它是先存到暫時儲存室,然後再真正寫到對應目錄的硬碟上, 按理來說當上傳一個檔案時,其實是上傳了兩份,第一個是以 .tem 格式的 * 然後再將其真正寫到對應目錄的硬碟上 */ factory.setRepository(dir); // 設定快取的大小,當上傳檔案的容量超過該快取時,直接放到暫時儲存室 factory.setSizeThreshold(1024 * 1024); // 高水平的API檔案上傳處理 // Collection<Part> parts =request.getParts(); ServletFileUpload upload = new ServletFileUpload(factory); String name=null; String path1=null; String houzui=null; try { List<FileItem> list = upload.parseRequest(request); FileItem picture = null; for (FileItem item : list) { // 獲取表單的屬性名字 String [] b=item.getFieldName().split(","); name = b[0]; path1=b[1]; houzui=item.getName(); // 如果獲取的表單資訊是普通的 文字 資訊 if (item.isFormField()) { // 獲取使用者具體輸入的字串 String value = item.getString(); request.setAttribute(name, value); System.out.println("name=" + name + ",value=" + value); } else { picture = item; } } String [] a= houzui.split("\\."); path=path+path1+"\\"+time+"\\"; // 自定義上傳圖片的名字為userId.jpg String fileName = name + "."+a[3]; String destPath = path + fileName; System.out.println("destPath=" + destPath); // 真正寫到磁碟上 File file = new File(destPath); File dir1 = new File(path); if (!dir1.exists()) { //建立完整的路徑包括不存在的父路徑 dir1.mkdirs(); } 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) { System.out.println(e1); } catch (Exception e) { System.out.println(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(); */