微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java Spring MVC 上传下载文件配置及controller方法详解

这篇文章主要介绍了Java Spring MVC 上传下载文件配置及controller方法详解,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下

下载:

1.在spring-mvc中配置(用于100M以下的文件下载)

下载文件代码

@RequestMapping("/file/{name.rp}") public ResponseEntity fileDownLoad(@PathVariable("name.rp")String name, HttpServletRequest request,HttpServletResponse response) { // @PathVariable String name, // @RequestParam("name")String name, // System.out.println(""+name); // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); ResponseEntity re = null; try { /** * css,js,json,gif,png,bmp,jpg,ico,doc,docx,xls,xlsx,txt,swf,pdf * **/ //下载防止静态加载干扰 Feelutile f=new Feelutile(); name=f.getfileformat(name); String pathString="C:\tempDirectory\"+name; File file=new File(pathString); HttpHeaders headers=new HttpHeaders(); //String filename=URLEncoder.encode(name, "UTF-8");//为了解决中文名称乱码问题 String filename=new String(name.getBytes("utf-8"),"utf-8"); byte[] by=FileUtils.readFiletoByteArray(file); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //URLEncoder.encode(filename, "UTF-8") headers.setContentdispositionFormData("attachment",filename); headers.setContentLength(by.length); re=new ResponseEntity(by, headers, HttpStatus.CREATED); } catch (Exception e) { e.printstacktrace(); try { request.getRequestdispatcher("/error/404.jsp").forward(request, response); } catch (servletexception e1) { // Todo Auto-generated catch block e1.printstacktrace(); } catch (IOException e1) { // Todo Auto-generated catch block e1.printstacktrace(); } } return re; }

上传文件:

1在spring-mvc中配置

UTF-8104857600040960

在controller中代码如下

@RequestMapping(value="/upload", method = RequestMethod.POST) @ResponseBody public Json upload(Doc doc, @RequestParam("uploadFile") Commonsmultipartfile file) { Json j = new Json(); try { String realpath = this.servletContext.getRealPath("/upload"); String uploadFileFileName = file.getoriginalFilename(); String uploadFileFileNameWithoutSpace = uploadFileFileName.replaceAll(" ", ""); String fileType = uploadFileFileNameWithoutSpace.substring(uploadFileFileNameWithoutSpace.lastIndexOf(".")); File targetFile = new File(realpath+File.separator, uploadFileFileNameWithoutSpace); if (targetFile.exists()) { targetFile.delete(); } file.getFileItem().write(targetFile); docService.upload(doc,uploadFileFileNameWithoutSpace); j.setSuccess(true); j.setMsg("Upload manual successfully"); }catch (Exception e) { logger.error(ExceptionUtil.getExceptionMessage(e)); j.setMsg("Upload manual unsuccessfully"); } return j; }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐