Spring MVC File Upload to folder (reprint + Experience)

Source: Internet
Author: User

A simple example of spring MVC (annotations) uploading a file, there are a few points to note
1.form enctype= "Multipart/form-data" This is required to upload files
2.applicationcontext.xml <bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver "/> File upload configuration is not limited

Applicationcontext.xml

[HTML]View Plaincopyprint?
  1. <? XML version= "1.0" encoding="UTF-8"?>
  2. <beans xmlns="Http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/ schema/p "
  4. xmlns:context="Http://www.springframework.org/schema/context"
  5. xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans-3.0.xsd
  6. Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "
  7. default-lazy-init="true">
  8. <!--start the annotation feature of spring MVC and complete the mapping of requests and annotations Pojo-
  9. <Bean class="Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" lazy-init="false" />
  10. <!--also better to join defaultannotationhandlermapping, otherwise it will be overwritten by XML or other mappings! -
  11. <Bean class="Org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  12. <!--resolution of the Model view name, that is, the model view name is added before and after
  13. <Bean class="Org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix= "/web-inf/jsp/" p:suffix= ". jsp" />
  14. <!--support upload file value means the size of the uploaded file--
  15. <bean id= "multipartresolver" class=" Org.springframework.web.multipart.commons.CommonsMultipartResolver ">
  16. <property name= "maxuploadsize" value= "10000000000000"/></bean>
  17. </Beans>

Uploadaction.java

[Java]View Plaincopyprint?
  1. Package com.codeif.action;
  2. Import Java.io.File;
  3. Import Java.util.Date;
  4. Import Javax.servlet.http.HttpServletRequest;
  5. Import Org.springframework.stereotype.Controller;
  6. Import Org.springframework.ui.ModelMap;
  7. Import org.springframework.web.bind.annotation.RequestMapping;
  8. Import Org.springframework.web.bind.annotation.RequestParam;
  9. Import Org.springframework.web.multipart.MultipartFile;
  10. @Controller
  11. Public class Uploadaction {
  12. @RequestMapping (value = "/upload.do")
  13. Public String Upload (@RequestParam (value = "File", required = false) Multipartfile file, HttpServletRequest request, Modelmap model) {
  14. System.out.println ("start");
  15. String path = Request.getsession (). Getservletcontext (). Getrealpath ("upload");
  16. String fileName = File.getoriginalfilename ();
  17. String fileName = new Date (). GetTime () + ". jpg";
  18. SYSTEM.OUT.PRINTLN (path);
  19. File TargetFile = new File (path, fileName);
  20. if (!targetfile.exists ()) {
  21. Targetfile.mkdirs ();
  22. }
  23. //Save
  24. try {
  25. File.transferto (targetfile);
  26. In this way, the above method can be uploaded, but it is always reported that the output stream is occupied error.
  27. Savefilefrominputstream (
    File.getinputstream (), Realpath + filePath, name + "." + FileType);
  28. } catch (Exception e) {
  29. E.printstacktrace ();
  30. }
  31. Model.addattribute ("FileUrl", Request.getcontextpath () +"/upload/" +filename);
  32. return "result";
  33. }
  34. }

The implementation of Savefilefrominputstream () is as follows:

public void Savefilefrominputstream (InputStream stream, String path,
String filename) throws IOException {
{//path + "/" + filename
FileOutputStream fs = new FileOutputStream (path + "/" + filename);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((Byteread=stream.read (buffer))!=-1)
{
Bytesum+=byteread;
Fs.write (Buffer,0,byteread);
Fs.flush ();
}
Fs.close ();
Stream.Close ();
}

index.jsp

[HTML]View Plaincopyprint?
  1. <%@ page pageencoding="utf-8"%>
  2. <! DOCTYPE HTML>
  3. <html>
  4. <head>
  5. <Meta charset="Utf-8">
  6. <title> Upload image </title>
  7. </head>
  8. <body>
  9. <form action= "upload.do"  method= "POST"  enctype= "Multipart/form-data" >  
  10. <input type="file" name="file" /> <input type="Submit" value= "Submit" /></form>
  11. </body>
  12. </html>


Spring MVC File Upload to folder (reprint + Experience)

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.