微信小程序+springboot后端实现图片上传

一.小程序

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{
        //接收参数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);
            //判断路径是否存在,如果不存在就创建一个
            if (!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path+File.separator + filename));
            System.out.println(filename);
            return "success";
        }else {
            return "error";
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容