Spring Boot 文件上传与下载

上传

@Controller
@Slf4j
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private Environment environment;
    @PostMapping(value = "/file")
    @ResponseBody
    public Response<String>  uploadFile(@RequestParam(value = "file")MultipartFile file,@RequestParam(value = "sessionId") String sessionId) throws IOException {
        boolean status = MySessionCheckUtil.checkSession(sessionId);
        String result = null;
        Response r = new Response();
        if(status){
            String oldFileName = file.getOriginalFilename();
            String oldFileNameType = oldFileName.substring(oldFileName.lastIndexOf('.'));
            String newFileName = UUID.randomUUID().toString()+oldFileNameType;
            boolean uploadStatus = false;
            if(SystemUtils.isOSLinux()){
                uploadStatus = FileUtil.uploadFile(file.getBytes(),environment.getProperty("linux.filePath"),newFileName);
            }else {
                uploadStatus = FileUtil.uploadFile(file.getBytes(),environment.getProperty("window.filePath"),newFileName);
            }
            if(uploadStatus){
                log.info(newFileName+" upload success");
                result = newFileName;
                r.setResult(result);
                r.setCode(1);
                r.setMsg("upload success");
            }else{
                log.info(newFileName+" upload failed");
                r.setResult(result);
                r.setCode(1);
                r.setMsg("upload failed");
            }
        }
        return r;
    }
}

下载

@Controller
@Slf4j
@RequestMapping("download")
public class DownloadController {
    @GetMapping("/file/{fileName}")
    public void downloadFile(final HttpServletResponse response, @PathVariable(value = "fileName")String fileName) throws IOException {
        String name = "D:\\newsImg\\387b5fe3-331a-4b40-9baf-0371255e85c2.PNG";
        byte bFile[] = FileUtil.readFile(name);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + bFile.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(bFile);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }
}
```
### FileUtil工具类
```
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;

@Slf4j
public class FileUtil {
    public static boolean uploadFile(byte []file, String filePath, String fileName) throws FileNotFoundException {
        if(file == null){
            throw new NullPointerException("Invalid file path");
        }
        if(filePath == null){
            throw new FileNotFoundException("Invalid file path");
        }
        boolean result = false;
        FileOutputStream out = null;
        try{
            /** get the file path */
            File targetFile = new File(filePath);
            /**check the path*/
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            log.info(filePath + fileName+"被写入");
            out = new FileOutputStream(filePath + fileName);
            out.write(file);
            out.flush();
            out.close();
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    public static byte[] readFile(String fileName) throws IOException {
        if(fileName==null){
            throw new NullPointerException("fileName is null");
        }
        File file = new File(fileName);
        if(!file.exists()){
            throw new FileNotFoundException("Invalid file path");
        }
        byte bFile[] = Files.readAllBytes(new File(fileName).toPath());
        return bFile;
    }
}
```
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值