這次給大家帶來微信小程序上傳圖片實戰案例解析,微信小程序上傳圖片實戰案例的注意事項有哪些,下面就是實戰案例,一起來看一下。愛掏網 - it200.com
在網上看了好多小程序上傳圖片,java后端接收的示例,但是不管在哪個網站看的,代碼基本是一樣的,都是代碼特別多。愛掏網 - it200.com
所以就自己寫一個比較簡單的。愛掏網 - it200.com
?一 小程序端
user.wxml
登錄后復制? ? ? ?? ? ?? ? 點擊選擇頭像 ?
user.js
//?更換頭像? span?style="font-size:18px;color:#FF0000;">?updateHead:?function?()?{? ??var?that?=?this? ??//?上傳圖片?獲取路徑? ??wx.chooseImage({? ???success:?function?(res)?{? ????console.log('臨時路徑:'?+?res.tempFilePaths[0])? ??????wx.uploadFile({? ???????url:?app.globalData.baseUrl?+?'/file/uploadFile',? ???????filePath:?res.tempFilePaths[0],? ???????name:?'file',? ???????success:?function?(result)?{? ????????console.log("返回路徑:"?+?result.data)? ???????}? ??????})? ???},? ??})? ?},登錄后復制
?二 java端
package?cn.helloxhs.moudle.common;? ? import?java.io.File;? import?java.io.FileInputStream;? import?java.io.FileNotFoundException;? import?java.io.FileOutputStream;? import?java.io.IOException;? import?java.io.InputStream;? import?java.io.OutputStream;? ? import?javax.servlet.http.HttpServletRequest;? import?javax.servlet.http.HttpServletResponse;? ? import?org.apache.commons.fileupload.disk.DiskFileItem;? import?org.springframework.stereotype.Controller;? import?org.springframework.web.bind.annotation.RequestMapping;? import?org.springframework.web.bind.annotation.ResponseBody;? import?org.springframework.web.multipart.MultipartFile;? import?org.springframework.web.multipart.commons.CommonsMultipartFile;? ? import?cn.helloxhs.base.controller.BaseController;? ? /**? ?*?類說明? ?*? ?*?@author?肖荷山? ?*?@version?創建時間:2024年12月23日?上午11:14:27? ?*/? @Controller? @RequestMapping("/file")? public?class?FileController?extends?BaseController?{? ??@RequestMapping("/uploadFile")? ??@ResponseBody? ??public?Object?uploadFile(HttpServletResponse?response,?HttpServletRequest?request,?MultipartFile?file)?{? ????String?realPath?=?request.getSession().getServletContext().getRealPath("/temp");? ????try?{? ??????CommonsMultipartFile?cf?=?(CommonsMultipartFile)?file;? ??????DiskFileItem?fi?=?(DiskFileItem)?cf.getFileItem();? ??????File?f1?=?fi.getStoreLocation();? ??????InputStream?ips?=?new?FileInputStream(f1);? ??????OutputStream?ops?=?new?FileOutputStream(realPath?+?"/"?+?"xhs.jpg");? ??????byte[]?b?=?new?byte[1024];? ??????int?len;? ??????try?{? ????????while?((len?=?ips.read(b))?!=?-1)?{? ??????????ops.write(b,?0,?len);? ????????}? ??????}?catch?(IOException?e)?{? ????????e.printStackTrace();? ??????}?finally?{? ????????//?完畢,關閉所有鏈接? ????????try?{? ??????????ops.close();? ??????????ips.close();? ????????}?catch?(IOException?e)?{? ??????????e.printStackTrace();? ????????}? ??????}? ? ????}?catch?(FileNotFoundException?e)?{? ??????e.printStackTrace();? ????}? ????return?realPath;? ??}? ? }登錄后復制
圖片存在了項目的temp目錄下
簡單就好,沒其他功能,單純上傳圖片。愛掏網 - it200.com
相信看了本文案例你已經掌握了方法,更多精彩請關注愛掏網 - it200.com其它相關文章!
推薦閱讀:
如何使用微信小程序做出圖片上傳
如何操作JS生成指隨機數與隨機序列
以上就是微信小程序上傳圖片實戰案例解析的詳細內容,更多請關注愛掏網 - it200.com其它相關文章!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。