springboot实现文件下载和文件上传

xiaoxiao2021-02-28  22

1.文件上传功能:直接看controller

@PostMapping("/uploadFile") public @ResponseBody String singleFileUpload(@RequestParam("file")MultipartFile file){ //判断文件是否为空 if(file.isEmpty()){ return "文件为空,上传失败!"; } try{ //获得文件的字节流 byte[] bytes=file.getBytes(); //获得path对象,也即是文件保存的路径对象 Path path= Paths.get(FILE_DIR+file.getOriginalFilename()); //调用静态方法完成将文件写入到目标路径 Files.write(path,bytes); return "恭喜上传成功!"; }catch (IOException e){ e.printStackTrace(); } return "未知异常"; }

其中FILE_DIR是上传文件的路径,可以自己根据选择设置,比如我这里设置FILE_DIR="f://file//" 这个路径

2.文件上传的html页面

<form method="POST" action="/uploadFile" enctype="multipart/form-data"> <input type="file" id="file_input"name="file" /><br/><br/> <input type="submit" value="Submit" /> </form>

OK,到这里,文件上传功能已经实现,那么现在是文件下载功能

3.直接看文件下载的Controller

@RequestMapping(value="/download",method = RequestMethod.GET) public void download( HttpServletResponse response){ //要上传的文件名字 String fileName="com.seven.xuanshang.apk"; //通过文件的保存文件夹路径加上文件的名字来获得文件 File file=new File(FILE_DIR,fileName); //当文件存在 if(file.exists()){ //首先设置响应的内容格式是force-download,那么你一旦点击下载按钮就会自动下载文件了 response.setContentType("application/force-download"); //通过设置头信息给文件命名,也即是,在前端,文件流被接受完还原成原文件的时候会以你传递的文件名来命名 response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", file.getName())); //进行读写操作 byte[]buffer=new byte[1024]; FileInputStream fis=null; BufferedInputStream bis=null; try{ 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(); } } } }

4.接下来是下载功能的html端的实现

<a href="/download">点击下载XX文件</a>5.至此,文件的upload和download功能已经完成

转载请注明原文地址: https://www.6miu.com/read-1449985.html

最新回复(0)