微信小程序+springboot后端實現(xiàn)圖片上傳

一.小程序

1.wxml代碼

<view>
  <button bindtap='fileUploadTap'>上傳</button>
</view>

2.js代碼

fileUploadTap: function(){
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'http://localhost:8080/upload', //僅為示例,非真實的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            description: '圖片'
          },
          success(res) {
            console.log(res.data)
          }
        })
      }
    })
  }

3.演示界面

image.png

點擊上傳按鈕,就可以選擇相應的圖片進行上傳

二.springboot后端

@RestController
public class TestController {
   // 上傳文件會自動綁定到MultipartFile
    @PostMapping(value="/upload")
    public String upload(HttpServletRequest request,
                         @RequestParam("description") String  description,
                         @RequestParam("file") MultipartFile file) throws Exception{
        //接收參數(shù)description
        System.out.println("description: " + description);
        //如果文件不為空,寫入上傳路徑
        if (!file.isEmpty()){
            //上傳文件路徑
            String path = request.getServletContext().getRealPath("/upload/");
            System.out.println("path = " + path);
            //上傳文件名
            String filename = file.getOriginalFilename();
            File filePath = new File(path, filename);
            //判斷路徑是否存在,如果不存在就創(chuàng)建一個
            if (!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdirs();
            }
            //將上傳文件保存到一個目標文件當中
            file.transferTo(new File(path+File.separator + filename));
            System.out.println(filename);
            return "success";
        }else {
            return "error";
        }
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容