Java Spring MVC upload download file configuration and controller method detailed _java

Source: Internet
Author: User

Download:

1. Configure in Spring-mvc (for download of files below 100M)

<bean class= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > 
< Property name= "Messageconverters" > 
<list> 
<!--Configure download return type-->
<bean class= " Org.springframework.http.converter.ByteArrayHttpMessageConverter "/> 
<bean class=" Org.springframework.http.converter.StringHttpMessageConverter "> 
<!--configuration encoding mode-->
<property Name= "Supportedmediatypes" value= "Application/json; Charset=utf-8 "/> 
</bean> 
</list> 
</property> 
</bean>

Download file code

@RequestMapping ("/FILE/{NAME.RP}") Public responseentity<byte[]> FileDownload (@PathVariable ("NAME.RP") String name, HttpServletRequest request,httpservletresponse response) {//@PathVariable String name,//@RequestParam ("N
Ame ") String name,//System.out.println (" <name> "+name); System.out.println (">>>>>>>>>>>>>>>>>>>>>>
>>>>>>>> ");
responseentity<byte[]> re = null; try {/** * css,js,json,gif,png,bmp,jpg,ico,doc,docx,xls,xlsx,txt,swf,pdf * **///download prevent static load interference 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");//To resolve the Chinese name garbled problem 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<byte[]> (by, headers, httpstatus.created); catch (Exception e) {e.printstacktrace (); try {request.getrequestdispatcher ("/error/404.jsp"). Forward (Request,
Response); The catch (servletexception E1) {//TODO auto-generated catch block E1.printstacktrace ();} catch (IOException E1) {//TOD
O auto-generated Catch block E1.printstacktrace ();
} return re; }

Upload file:

1 configured in SPRING-MVC

<!--4. File upload configuration files upload-->
<bean id= "Multipartresolver" class= "
Org.springframework.web.multipart.commons.CommonsMultipartResolver ">
<property name=" Defaultencoding " >
<value>UTF-8</value>
</property>
<property name= "Maxuploadsize" >
<value>1048576000</value>
</property>
<property name= "Maxinmemorysize" >
<value>40960</value>
</property>
</bean>

The code in controller is as follows

 @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; }

The above is a small series to introduce Java Spring MVC upload download file configuration and controller method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.