文件上传
Action
/**
* 文件上传util
*
* @param request
* @param file
* @return
* @throws IOException
*/
@RequestMapping("/upload")
@ResponseBody
public String upload(HttpServletRequest request, MultipartFile file,Model model) throws IOException {
if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
String filenames = null;
String contextPath = request.getSession().getServletContext().getContextPath();
String upaloadUrl = request.getSession().getServletContext().getRealPath("/") + "ajaxupload";
//上传文件名
String filename = file.getOriginalFilename();
Random r = new Random();
StringBuffer buf = new StringBuffer();
for (int x = 0; x < 3; x++) { //循环取得三个不大于10的随机整数
buf.append(r.nextInt(10));
}
filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + buf.toString() + filename.substring(filename.lastIndexOf("."));
File filepath = new File(upaloadUrl, filename);
//判断路径是否存在
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
String fileNames = null;
//将上传文件保存到一个目标文件中
request.getSession().setAttribute("img", "1");
file.transferTo(new File(upaloadUrl + File.separator + filename));
fileNames = contextPath + "/ajaxupload/" + filename;
hello.setHelloname(fileNames);
hello.setHellopath(file.getOriginalFilename());
int n=helloService.addHello(hello);
model.addAttribute(file.getOriginalFilename(),"filename");
/* ModelAndView mv=new ModelAndView();
mv.setViewName("excal.html");*/
return fileNames;
} else {
return null;
}
}
文件下载
Action
public String download(HttpServletRequest request) throws IOException {
try {
ServletContext servletContext=request.getSession().getServletContext();
String realPath=servletContext.getRealPath("/ajaxupload");
System.out.println(realPath);
/* HttpServletResponse response = ServletActionContext.getResponse();*/
String filename =request.getParameter("filename");
// path是指欲下载的文件的路径。
File file = new File(realPath+"\\"+filename);
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(realPath+"\\"+filename ));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
String filenameString = new String(filename.getBytes("utf-8"),
"iso-8859-1");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenameString);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response
.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}