Spring boot之文件上传与下载

思路

  • 上传:文件通过MultipartFile接收
  • 下载:返回类型为ResponseEntity<Resource>,spring boot才能能够正确转化

代码

package top.sidian123.blog.media;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.sidian123.blog.Utils.Status;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author sidian
 * @date 2019/5/26 19:23
 */
@RestController
@RequestMapping("/image")
public class ImageController {
    @Autowired
    ImageService imageService;

    static Logger logger= LogManager.getLogger();

    /**
     * 获取图片
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<Resource> get(@PathVariable int id){
        //获取图片
        Image image=imageService.get(id);
        if(image==null){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        //返回响应
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+URLEncoder.encode(image.getName(), StandardCharsets.UTF_8)+"\"")
                .header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_OCTET_STREAM_VALUE)
                .body(new InputStreamResource(image.content));
    }

    /**
     * 接收上传的图片
     * @param file
     * @return 正常返回结果中携带id
     */
    @PostMapping("/upload")
    public Status upload(@RequestParam MultipartFile file){
        //创建image对象
        Image image=new Image();
        image.setName(file.getOriginalFilename());
        try {
            image.setContent(file.getInputStream());
        } catch (IOException e) {
            logger.catching(e);
            return Status.from(301,"读取失败");
        }
        //存储
        imageService.store(image);
        //返回结果
        return Status.from(0,"ok",image.id);
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值