文件上传
前台页面的编写
<form action="/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="userName">
<input type="submit">
</form>
Controllser层的编写
@ResponseBody
@RequestMapping(value = "upload",method = RequestMethod.POST)
public String upload(HttpServletRequest request) throws Exception {
MultipartFile file = null;
String fileName = null;
try {
System.out.println("用户名:" + request.getParameter("userName"));
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest mrequest = resolver.resolveMultipart(request);
file = mrequest.getFile("file");
fileName = file.getOriginalFilename();
} catch (MultipartException e) {
e.printStackTrace();
}
System.out.println("文件名:" + fileName);
//通过字节输出流写入
String realPath = request.getRealPath("/upload");
System.out.println("文件要上传的路径为:" + realPath);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
String format = dateFormat.format(new Date());
FileOutputStream fos = new FileOutputStream(realPath+"/upload"+format+fileName.substring(fileName.lastIndexOf(".")));
fos.write(file.getBytes());
fos.flush();
fos.close();
return "upload";
}
将HttpServletRequest转换成MultiparResolver的两种方式
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest)request;
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest mrequest = resolver.resolveMultipart(request);
文件下载
前台页面的编写
<a href="/down.do?filename=test.txt">测试文件下载</a>
Controllser层的编写
@RequestMapping("down")
public void download(HttpServletRequest request,HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8");
response.setContentType("html/text;charset=utf-8");
//获得从前端传递过来的文件名
String filename = request.getParameter("filename");
//获得项目的绝对路径
String realPath = request.getRealPath("upload/");
File file = new File(realPath, filename);
System.out.println(file.toPath());
//设置响应类型 ==》 告诉浏览器当前是下载操作,我要下载东西
response.setContentType("application/x-msdownload");
//设置下载时文件的显示类型(即文件名称-后缀) ex:txt为文本类型
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
FileInputStream fis = new FileInputStream(realPath+filename);
ServletOutputStream os = response.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len=fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
fis.close();
}