JAVA开发上传下载本地文件DEMO

编程入门 行业动态 更新时间:2024-10-27 06:18:35

JAVA开发<a href=https://www.elefans.com/category/jswz/34/1760739.html style=上传下载本地文件DEMO"/>

JAVA开发上传下载本地文件DEMO

 @RequestMapping(value = "/load",method = RequestMethod.POST)public void upload(HttpServletRequest req,HttpServletResponse res,@RequestParam("file") MultipartFile file){if(file.isEmpty()){throw new ToUserException("上传文件为空!");}Long time  = System.currentTimeMillis();try {String orginateFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");System.out.println("导入原始文件名:"+orginateFileName);System.out.println("导入原始文件大小:"+file.getSize());String fileName = time+"_"+orginateFileName;File localFile = new File("D://"+fileName);file.transferTo(localFile);ServletUtils.toJson(fileName,req,res);} catch (Exception e) {e.printStackTrace();}}@GetMapping("/downLoad")public void download(String id, HttpServletRequest request, HttpServletResponse response) {System.out.println(id);try (FileInputStream inputStream = new FileInputStream(new File("D://"+id));ServletOutputStream outputStream = response.getOutputStream();) {// 声明响应类型response.setContentType("application/x-download");// 下载的文件名称response.addHeader("Content-Disposition", "attachment;filename="+id);IOUtils.copy(inputStream, outputStream);//ServletUtils.toJson(request,response);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

直接贴的代码,有问题可以留言,demo版比较简单!
遇到问题1:请求报400 问题排查

  1. 需要消息头 Content-Type 设置为 multipart/form-data;
  2. spring需要配置文件解析器 配置如下 <!-- 定义文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipartmons.CommonsMultipartResolver"> <!-- 设定默认编码 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 设定文件上传的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880" /> <property name="maxInMemorySize" value="4096" /> </bean>

更多推荐

JAVA开发上传下载本地文件DEMO

本文发布于:2024-03-05 01:27:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1710953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传下载   本地文件   JAVA   DEMO

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!