vue + springboot 上传图片到后台

我想在前台上传代码到后台,然后数据库可以保存,前台也可以调用,我从网上搜了代码,但现在不知道后端的controller应该在原来的controller里写,还是新建一个controller?
我尝试了新建一个controller放新的代码,然后点击捐赠之后还是成功了,但是图片不知道上传到哪里去了,可以请大家帮忙看一下哪里有问题吗?
前台代码如下:

                
                  <el-col :span="8">
                    <el-form-item label="物资图片" prop="unit">
                      <el-upload
                          accept="image/jpeg,image/png"
                          :on-preview="handlePreview"
                          :on-remove="handleRemove"
                          :before-remove="beforeRemove"
                          ref="upload"
                          action=""
                          :http-request="upload"
                          :auto-upload="false"
                          :before-upload="onBeforeUpload"
                          multiple
                          :limit="1"
                          :on-exceed="handleExceed"
                          v-model="addForm.pictures">
                        <el-button size="small" type="primary">点击上传el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1Mdiv>
                      el-upload>
                    el-form-item>
                  el-col>
                

                <el-form-item>
                  <el-button type="primary" @click="addIn">立即捐赠el-button>
                el-form-item>


 addIn() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const {data: res} = await this.$http.post("addIn2", this.addForm);
        if (res != "success") {
          return this.$message.error("捐赠失败~");
        }
        this.$message.success("捐赠成功~");
        this.addDialogVisible = false;
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }?`);
    },
    onBeforeUpload(file)
    {
      const isIMAGE = file.type === 'image/jpeg'||'image/png';
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
      }
      return isIMAGE && isLt1M;
    },
    upload (file) {
      const _this = this
      let formdata = new FormData()

      // 上传图片并转成Base64编码
      formdata.append('files', file.file)
      console.log(formdata)

      this.$axios.post('/uploadImage', formdata).then((resp) => {
        if (resp.status === 200) {
          console.log(resp.data)
          // 设置图片回显
          _this.form.logo = resp.data
          _this.$message({type: 'success', message: '图片上传成功!'})
        }
      }).catch(() => {
        this.$message({type: 'info', message: '图片太大或格式有误,上传失败,请重新上传!'})
      })
    }
  }

原controller代码如下:

@RequestMapping("/addIn2")
    public String addIn2(@RequestBody InStock inStock){
        inStock.setState(0);
        inStock.setFromwho(2);
        int i = inStockDao.addIn(inStock);
        return i > 0 ? "success":"error";
    }

新controller如下:

@RequestMapping(value = "/api/uploadImage", method = RequestMethod.POST)
    public String uploadImage(@RequestParam("files") MultipartFile file) throws IllegalStateException, IOException {
        System.out.println(file.getOriginalFilename() + "图片已传入!!");
        byte[] b = file.getBytes();
        String str = Base64.getEncoder().encodeToString(b);
        return "data:image/jpeg;base64," + str;
    }

以下内容部分参考ChatGPT模型:


首先,你需要在后端新建一个controller来处理上传图片的请求。你可以参考你已经写好的新controller代码,稍微做一些修改,使得它能够将上传的图片保存到你的服务器上。例如:

@RequestMapping(value = "/api/uploadImage", method = RequestMethod.POST)
@ResponseBody
public String uploadImage(@RequestParam("files") MultipartFile file) throws IOException {
    System.out.println(file.getOriginalFilename() + "图片已传入!!");
    byte[] b = file.getBytes();
    String fileName = file.getOriginalFilename();
    Path path = Paths.get("your_upload_folder/" + fileName);
    Files.write(path, b);
    return fileName;
}

在这个例子中,我们首先获取上传的文件的字节数组,然后将文件保存到指定的文件夹中。你需要将 "your_upload_folder" 替换为你实际希望存储图片的文件夹路径。

在前端代码中,你需要将上传图片的请求地址改成你的后端controller的地址。例如:

<el-upload
  accept="image/jpeg,image/png"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  ref="upload"
  :action="'your_backend_url/api/uploadImage'"
  :http-request="upload"
  :auto-upload="false"
  :before-upload="onBeforeUpload"
  multiple
  :limit="1"
  :on-exceed="handleExceed"
  v-model="addForm.pictures">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1M</div>
</el-upload>

在这个例子中,我们将 ":action" 的值设置成了你的后端controller的地址。你需要将 "your_backend_url" 替换成你实际的后端接口地址。

当你上传图片时,它应该会被保存到你指定的文件夹中。你可以在你的代码中使用这个文件路径来访问图片。例如,在你的前端代码中,你可以这样显示图片:

<img :src="'your_upload_folder/' + addForm.pictures" />

这将根据你保存图片的文件夹和上传的文件名来构建图片的URL。你需要将 "your_upload_folder" 替换为你实际的图片文件夹路径。

这就是解决你的问题的思路。你需要在后端处理上传图片的请求,并保存图片到服务器上。在前端,你需要将上传图片的请求地址设置成你的后端controller的地址,并使用你保存图片的文件路径来访问图片。


如果我的建议对您有帮助、请点击采纳、祝您生活愉快

可以通用一个controller的,在一个类里面写多个方法即可。图片上传位置可以通过在后端debug可以找到。而且看uploadImage代码,图片并没有写入到本地磁盘中。只是用MultipartFile对象接收了参数而已

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7588561
  • 除此之外, 这篇博客: vue及springboot前后端分离实现微信公众号授权、自定义菜单、订阅推送消息中的 controller 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
        /**
         * 微信公众号立刻更新使用当前配置的菜单
         * @return
         */
        @PreAuthorize("@ss.hasAnyPermi('wxapp:wxAppMenu:UseCurrentConfigure')")
        @Log(title = "微信公众号更新使用当前菜单" , businessType = BusinessType.OTHER)
        @GetMapping("/UseCurrentConfigure")
        public AjaxResult UseCurrentConfigure(){
            WxAppMenu wxAppMenu = new WxAppMenu();
            wxAppMenu.setWxMenuStatus("0");
            List<WxAppMenu> menus = iWxAppMenuService.selectWxAppMenuList(wxAppMenu);
            String menuJson =WxAppMenuUtils.getMenuJson(menus);
            String accessToken = WxAppMenuUtils.getAccessToken();
            String message = "微信公众号菜单更新失败!原因: accessToken或者menuJson(数据库菜单json)出错!";
            if(!StrUtil.hasEmpty(accessToken) && !StrUtil.hasEmpty(menuJson)){
                int result = WxAppMenuUtils.setWxAppMenu(accessToken,menuJson);
                if(result == 0){
                    return AjaxResult.success("微信公众号菜单已更新!");
                }else{
                    message="微信公众号菜单更新失败!原因: 可能MENU_CREATE_URI请求出错。";
                }
            }
            return AjaxResult.error(message);
        }
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^