java spring mvc 上传_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中配置
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
UTF-8
1048576000
40960
在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;
}
以上所述是小編給大家介紹的Java Spring MVC 上傳下載文件配置及controller方法詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對聚米學院網站的支持!
總結
以上是生活随笔為你收集整理的java spring mvc 上传_Java Spring MVC 上传下载文件配置及controller方法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 交个朋友公布三周年成绩单:合作品牌超1万
- 下一篇: 验证码拦不住机器人了,谷歌 AI 已能精