uniapp上传图片前后端代码


1.后端java代码:

    /**
     * 图片上传
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(HttpServletRequest request) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            // 对应前端的upload的name参数"file"
            MultipartFile file = req.getFile("file");
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            Map result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("url", url);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

2.前端代码:

uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['camera', 'album'], //这要注意,camera调拍照,album是打开手机相册
    success: (res) => {
        // 页面展示
        that.image1 = res.tempFilePaths[0];
        uni.uploadFile({
            url: 'http://localhost:8081/app/upload', //post请求的地址
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: {},
            header: {
                Authorization: that.authtoken
            },
            success: (myres) => {
                console.log(myres);
                 var jsonObject = JSON.parse(myres.data);
                if (jsonObject.code == 200) {
                    var imageUrl = jsonObject.data.url;
                    // 后端存储url
                    that.resultForm.subManSign = imageUrl;
                }
            }
        })
    }
});

以上;