代码已经上传至gitee

https://gitee.com/hashuaiboy/file-upload-demo

思路

使用 MultipartFile 文件类

  String str = "E://images/";
    @RequestMapping("/uploads")
    public String FileUploads(HttpServletRequest request, MultipartFile file) {
        String originalname = file.getOriginalFilename();
        // 获取后缀
        String newName = originalname.substring(originalname.lastIndexOf("."));
        // 捕获后缀非jpg的文件
        if (!".jpg".equals(newName)){
            return "error";
        }
        newName = String.valueOf(new Random().nextInt(50)) + newName;
        File newFile = new File(str, newName);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdir();
        }
        try {
            file.transferTo(newFile);
            // save new upload file to database
            files newfile = new files();
            newfile.setFilename(newName);
            newfile.setCreatetime(String.valueOf(new Date()));
            fileService.save(newfile);


        } catch (IllegalStateException | IOException exception) {
            exception.printStackTrace();
        }
        return str + newName;
    }
 <el-upload
        style="margin-top: 50px"
        class="upload-demo"
        ref="upload"
        :on-preview="handlePictureCardPreview"
        action="http://localhost:8081/api/uploads"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        list-type="picture-card"
        :file-list="fileList"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :multiple="false"
        :limit="1"
        :before-upload="beforeAvatarUpload"
      >
       <i class="el-icon-plus"></i>
      </el-upload>

使用 Elementui 事半功倍

PS:图片文件会被存储到 E://images中

END

有问题请联系feinan6666@outlook.com

本文作者:
文章标题:springboot后端文件上传接口的书写
本文地址:https://home.cnboy.top/image-upload.html
版权说明:若无注明,本文皆神码人の世界原创,转载请保留文章出处。
最后修改:2022 年 06 月 13 日 08 : 04 PM
如果觉得我的文章对你有用,请随意赞赏