The first step:
Adding support in Applicationcontext.xml
<!--support File upload--
<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
</bean>
Step Two:
/**
* Upload Files
*
* @param file
* @param request
* @param model
* @return
*/
@RequestMapping (value = "/upload")
Public String Upload (@RequestParam (value = "File", Required = False) Multipartfile file, httpservletrequest request, Model Map model) {
Returns uploadtxt.jsp if the file is empty
if (File.isempty ()) {
return "Uploadtxt";
}
System.out.println ("Start upload file");
String path = Request.getsession (). Getservletcontext (). Getrealpath ("Upload");
String fileName = File.getoriginalfilename ();
If the file format is not txt, return uploadtxt.jsp
if (!filename.endswith ("TXT")) {
return "Uploadtxt";
// }
System.out.println ("filename====>" + fileName);
String fileName = new Date (). GetTime () + ". jpg";
System.out.println ("File path:" + path);
File TargetFile = new file (path, fileName);
if (!targetfile.exists ()) {
Create a Directory
Targetfile.mkdirs ();
}
try {
File.transferto (targetfile);
} catch (Exception e) {
E.printstacktrace ();
}
Model.addattribute ("FileUrl", Request.getcontextpath () + "/upload/" + fileName);
return "Forward:/list";
}
/**
* Get all files on the upload path
*
* @param request
* @return
*/
@RequestMap Ping ("/ListFile")
Public modelandview list (HttpServletRequest request) {
String FilePath = Request.getse Ssion (). Getservletcontext (). Getrealpath ("/") + "upload/";
Modelandview Modelandview = new Modelandview ();
File Uploaddest = new file (FilePath);
string[] fileNames = Uploaddest.list ();
//for (int i = 0; i < filenames.length; i++) {
///Output all file names
//System.out.print ln (filenames[i]);
//}
String jsonstring = json.tojsonstring (fileNames);
Modelandview.addobject ("filenamesjsonstring", jsonstring);
System.out.println (jsonstring);
Modelandview.setviewname ("ListFile");
return modelandview;
}
/**
* Download File
*
* @param request
* @param fileName
* @return
* @throws IOException
*/
@RequestMapping ("/download")
Public responseentity<byte[]> Download (httpservletrequest request, @RequestParam ("filename") String fileName) Throws IOException {
String path = Request.getservletcontext (). Getrealpath ("/upload/");
File Dwfile = new file (path + file.separator + fileName);
Httpheaders headers = new Httpheaders ();
Download the displayed Chinese name, solve the Chinese name garbled problem
String downloadfilename = new String (Filename.getbytes ("UTF-8"), "iso-8859-1");
Application/octet-stream: Binary Stream data
Headers.setcontentdispositionformdata ("Attachment", downloadfilename);
Headers.setcontenttype (Mediatype.application_octet_stream);
return new Responseentity<byte[]> (Fileutils.readfiletobytearray (dwfile), headers, httpstatus.created);
}
Springmvc implement upload and download files