SPRINGMVC (6) File upload

Source: Internet
Author: User
Tags save file uuid

SPRINGMVC (6) File upload

We do an example of uploading images, the page (fileupload.jsp) function is as follows: Upload successfully immediately after uploading the image. UPLOAD.JSP:
<body><form action= "/testannotationmvc_fileupload/file/fileupload2.jspx"method= "POST" enctype= "Multipart/form-data" ><input type= "file" name= "file"/><input type= "Submit" value= "Upload"/></form></body>
In the form form, enctype= "Mulitpart/form-data" is required, and method must be post, don't forget it. Specially searched this thing, below is the explanation on the W3cschool website: HTML enctype attribute 1) His role is to set the MIME encoding of the form, by default, this encoding format is application/x-www-form-urlencoded, cannot be used for file upload; only multipart/form-data can be used to transfer the file data completely. 2) enctype= "Multipart/form-data" is to upload binary data; The value of input in the form is passed in 2 binary ways. It is not possible to use Request.getparameter () to get the values of individual form elements when a form request is passed to another JSP or servlet. When uploading using Multipart/form-data, the request sent is different from the normal HTTP, which requires conversion before other parameters can be read.  In addition, we need to import two dependent commons packages: Org.apache.commons.fileupload-1.2.0.jarorg.apache.commons.io-1.4.0.jar one, the traditional way of file flowto create a new Fileuploadcontroller, there are two methods:tofile ()---Jump to the uploaded JSP pagefileUpload ()---File Upload out of processing class
@Controller@RequestMapping ("/file")Public class Fileuploadcontroller {    @RequestMapping ("/tofile")//Jump to File upload jsp pagePublic String Tofileupload () {return "FileUpload";    }    @RequestMapping ("/fileupload")Public String FileUpload (@RequestParam ("file") commonsmultipartfile file,httpservletrequest request, Modelmap model) {        //Get original file nameString fileName = File.getoriginalfilename ();System.out.println ("filename:" + filename);        //New file nameString newfilename = Uuid.randomuuid () +filename;        //upload to whereString Path = "d:/upload/";file F = new file (path);if (!f.exists ()) f.mkdirs ();if (!file.isempty ()) {try {FileOutputStream fos = new FileOutputStream (path+newfilename);InputStream in = File.getinputstream ();int b = 0;While ((B=in.read ())!=-1) {Fos.write (b);                }fos.close ();in.close ();} catch (Exception e) {e.printstacktrace ();            }        }System.out.println ("Imgurl:" + path+newfilename);//Save file Address for JSP page EchoModel.addattribute ("FileUrl", path+newfilename); return "FileUpload";    }
Second, the SPRINGMVC provides Multirequestresolver upload methodSpring expands on the HttpServletRequest interface of the Servlet API to allow it to handle file uploads well. The extended interface name is:Org.springframework.web.multipart.MultipartHttpServletRequest
Multiparthttpservletrequest mrequest = (multiparthttpservletrequest) (request);
the parameters can then be read normally: Mrequest.getparameter ("xxx"); We're going to add a fileUpload2 method to the Fileuploadcontroller :
@RequestMapping ("/fileupload2")Public String fileUpload2 (httpservletrequest request,httpservletresponse response) throws exception{commonsmultipartresolver CMR = new Commonsmultipartresolver (Request.getservletcontext ());if (Cmr.ismultipart (Request)) {multiparthttpservletrequest mrequest = (multiparthttpservletrequest) (request);iterator<string> files = mrequest.getfilenames ();While (Files.hasnext ()) {multipartfile mfile = Mrequest.getfile (Files.next ());if (mfile! = null) {String fileName = Uuid.randomuuid () +mfile.getoriginalfilename ();String Path = "d:/upload/" +filename;                file LocalFile = new file (path);Mfile.transferto (localfile);Request.setattribute ("FileUrl", path);            }        }    }return "FileUpload";}
So we're done uploading the file.

SPRINGMVC (6) File upload

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.