Java file upload and download

@GetMapping("/upload")
public void upload(MultipartFile file) throws IOException {
    
    
    String path = "";//上传的路径
    File file1 = new File(path);
    if (!file1.exists()) {
    
    
        //路径不存在就创建路径
        file1.mkdir();
    }
    file.transferTo(new File(file1 + "/" + file.getOriginalFilename()));
}

@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
    
    
    String path = "";//文件的下载地址
    String name = "";//要下载的文件名
    //设置响应头
    response.reset();//设置页面不缓存
    response.setCharacterEncoding("UTF-8");//字符集编码
    response.setContentType("multipart/form-data");//二进制传输文件
    response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));//设置响应头
    File file = new File(path, name);
    //输入流
    FileInputStream inputStream = new FileInputStream(file);
    //输出流
    ServletOutputStream outputStream = response.getOutputStream();

    byte[] bytes = new byte[10240000];
    int index = 0;
    while ((index = inputStream.read(bytes)) != -1) {
    
    
        outputStream.write(bytes, 0, index);
        outputStream.flush();
    }
    outputStream.close();
    inputStream.close();
}

Guess you like

Origin blog.csdn.net/weixin_45481406/article/details/109230395