SpringBoot文件上传下载

前言

博主github

博主个人博客http://blog.healerjean.com

习惯了使用OSS傻瓜式上传,是不是都快忘记写原生的上传了,今天小米的项目中需要用一下,所以之类简单总结下 吧

MultipartFile file 方法名字 内容
file.getContentType() image/png
file.getOriginalFilename() AAAA.png
file.getName() file

1、上传

1、FileUtils.copyInputStreamToFile

File localFile = new File(tempFile,fileName);
FileUtils.copyInputStreamToFile(file.getInputStream(),localFile);

2、file.transferTo

我使用这种方式报错了,没有深入研究,网上说是jar包问题

<dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    	<version>1.3.1</version>
</dependency>



File localFile = new File(tempFile,fileName);
file.transferTo(localFile);

3、正常读取

byte[] bytes = file.getBytes();
 
File localFile = new File(tempFile,fileName);

BufferedOutputStream stream = new BufferedOutputStream(
    new FileOutputStream(localFile));

stream.write(bytes);




BufferedOutputStream out = new BufferedOutputStream(
    new FileOutputStream(localFile));
in = file.getInputStream();
int num = 0;
byte[] b = new byte[1024];
while((num = in.read(b)) != -1) {
    out.write(b, 0, num);
}

 @Override
    public String upload(MultipartFile file){

        String name = UUID.randomUUID().toString().replaceAll("-", "");
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String localTime = df.format(dateTime);

        //文件存储最终目录
        File tempFile = new File("/User/healerjean/Desktop"+localTime);
        if(!tempFile.exists()){
            tempFile.mkdirs();
        }
        
        String fileName = file.getOriginalFilename();
        fileName = name+fileName.substring(fileName.lastIndexOf(".") );
        
        File localFile = new File(tempFile,fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),localFile);
            
        
            //2、 file.transferTo(localFile);
            
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
      return fileName;
    }

2、下载

@GetMapping("/{id}")
public void downLoad(HttpServletResponse response,String folder) {
    try {
        InputStream inputStream = new FileInputStream(new File(folder));
        OutputStream outputStream = response.getOutputStream();

        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=test.txt");

        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
    } catch (Exception e) {

    }
}



感兴趣的,欢迎添加博主微信

哈,博主很乐意和各路好友交流,如果满意,请打赏博主任意金额,感兴趣的在微信转账的时候,备注您的微信或者其他联系方式。添加博主微信哦。

请下方留言吧。可与博主自由讨论哦

微信 微信公众号 支付宝
微信 微信公众号 支付宝
posted @ 2019-04-26 17:54  HealerJean  阅读(131)  评论(0编辑  收藏  举报