后端文件上传及下载

1、upload.html中上传组件

<el-upload class="avatar-uploader"
     action="/common/upload"
     :show-file-list="false"
     :on-success="handleAvatarSuccess"
     :before-upload="beforeUpload"
     ref="upload">

     <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
    <script>
      new Vue({
        el: '#food-add-app',
        data() {
          return {
            imageUrl: ''
          }
        },
        methods: {
          handleAvatarSuccess (response, file, fileList) {
              this.imageUrl = `/common/download?name=${response.data}`
          },
          beforeUpload (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          }
        }
      })
    </script>

2、Controlller

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${file-upload.address}")
    private String fileAddress;

    @PostMapping("/upload")
    public R load(MultipartFile file) throws IOException {
        log.info("图片上传...");

        File f = new File(fileAddress);
        if(!f.exists()){
            f.mkdirs();
        }
        //截取图片后缀名
        String fileSuffer = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 生成的uuid+当前时间戳+图片后缀  = 图片名
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis() + fileSuffer;

        // 储存到电脑路径
        file.transferTo(new File(fileAddress + fileName));
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(fileAddress + name));
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3、application.yml

file-upload:
  address: E:\code\workspace\upload\

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值