SpringBoot文件上传下载

182 阅读1分钟

上传

@RequestMapping("/upload")
public static String upload(@RequestPart(value = "resource") MultipartFile file){

    String path ="C:/Users/hp/Desktop";
    //获取文件名后缀
    String fileLastType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

    //生成文件名称
    String uuid = UUID.randomUUID().toString();

    // 生成新的文件名
    String realPath = path + "/" + uuid + fileLastType;
    //使用原文件名
    //String realPath = path + "/" + file.getOriginalFilename();

    File dest = new File(realPath);

    //判断文件父目录是否存在
    if(!dest.getParentFile().exists()){
        dest.getParentFile().mkdir();
    }

    try {
        //保存文件
        file.transferTo(dest);
        return uuid + fileLastType;
    } catch (Exception e) {
        log.error(e.toString());
        return "error";
    }
}

下载

@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {
    String filename = "testfile.txt";
    
    response.setHeader("Content-Disposition", "attachment;filename=" + filename); 
    
    InputStream fis = new FileInputStream(new File("C:/Users/hp/Desktop/xx.txt")); 
    
    ServletOutputStream outputStream = response.getOutputStream();

    byte[] data = new byte[2048];
    int len = -1;
    while ((len = fis.read(data)) != -1) {
        outputStream.write(data, 0, len);
    }

    outputStream.flush();
    outputStream.close();
    fis.close();
}