Springmvc implement upload and download files

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.