上传下载本地文件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 问题排查
- 需要消息头 Content-Type 设置为 multipart/form-data;
- 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
发布评论