Spring Boot文件上传和下载

1. 文件上传

  1. 前端HTML
<form method="POST" action="/uploadFile" enctype="multipart/form-data">
    <br/><br/>
    <input type="submit"  value="Submit" />
form>
  1. 后端Controller
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) {
	if(file.isEmpty()) {
		return; 
	}
	
	String fileName = file.getOriginalFilename(); // 获取文件名,并对文件名进行修改
	String filePath = "E:\\file\\";
	File uploadFile = new File(filePath + fileName);
	try {
		if (!uploadFile.getParentFile().exists()) {
			uploadFile.getParentFile().mkdirs();
        }
		
		file.transferTo(uploadFile);
		LOGGER.info("上传文件成功");
	} catch (IOException e) {
		LOGGER.error("upload", e.getMessage());
	}
}

2.文件下载

  1. 前端HTML
下载文件a>
  1. 后端Controller
  @RequestMapping(value="/download",method = RequestMethod.GET)
    public void download(HttpServletRequest request, HttpServletResponse response){
		// 要上传的文件名字
		String fileName = request.getParameter("filename");
        //通过文件的保存文件夹路径加上文件的名字来获得文件
        File file=new File("E:\\file",fileName);
        //当文件存在
        if(file.exists()){
            try{
            	//首先设置响应的内容格式是force-download,那么你一旦点击下载按钮就会自动下载文件了
            	response.setContentType("application/force-download");
            	//通过设置头信息给文件命名,也即是,在前端,文件流被接受完还原成原文件的时候会以你传递的文件名来命名
            	response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            	
                //进行读写操作
            	byte[]buffer=new byte[1024];
           		FileInputStream fis=null;
           	 	BufferedInputStream bis=null;
                fis=new FileInputStream(file);
                bis=new BufferedInputStream(fis);
                OutputStream os=response.getOutputStream();
                //从源文件中读
                int i=bis.read(buffer);
                while(i!=-1){
                    //写到response的输出流中
                    os.write(buffer,0,i);
                    i=bis.read(buffer);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                //善后工作,关闭各种流
                try {
                    if(bis!=null){
                        bis.close();
                    }
                    if(fis!=null){
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

你可能感兴趣的:(Java)