java中的接口是类吗
599
2023-07-04
Java Spring MVC 上传下载文件配置及controller方法详解
下载:
1.在spring-mvc中配置(用于100M以下的文件下载)
下载文件代码
@RequestMapping("/file/{name.rp}")
public ResponseEntity
// @PathVariable StringHAzPJYYxpw name,
// @RequestParam("name")String name,
// System.out.println("
// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
ResponseEntity
try {
/**
* css,js,json,gif,png,bmp,jpg,ico,doc,docx,xls,xlsx,txt,swf,pdf
*http:// **/
//下载防止静态加载干扰
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
} 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">
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
在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方法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~