Using spring's multipartfile to implement file upload "original"

Source: Internet
Author: User

Using spring's multipartfile to implement file uploads is primarily dependent on the jar package

Spring-web-3.0.6.release.jar (Org.springframework.web.multipart.MultipartFile)
Commons-fileupload-1.3.1.jar
Commons-logging-1.0.4.jar

Front desk
<!DOCTYPE HTML><HTMLLang= "en"><Head><MetaCharSet= "Utf-8"><title>Upload</title><styletype= "Text/css"></style></Head><Body>    <formenctype= "Multipart/form-data"Action= "/kingtool/file/upload.do"Method= "POST">File:<inputtype= "File"name= "File" />        <inputtype= "Submit"value= "Submit" />    </form></Body></HTML>

Background
 PackageCom.bobo.code.web.controller;ImportJava.io.File;Importjava.io.IOException;ImportJava.math.BigDecimal;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.ModelMap;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.RequestParam;Importorg.springframework.web.multipart.MultipartFile; @Controller @requestmapping ({"File/*" }) Public classLogincontroller {/*** Underwriting Document Upload * *@paramSession*/@RequestMapping (Value= "Upload.do", method ={requestmethod.post, requestmethod.get}) Public voidFileUpload (HttpSession session, Modelmap Modelmap, httpservletresponse response, httpservletrequest request, @ Requestparam ("file") Multipartfile file)throwsException, IOException {String ret= ""; Request.setcharacterencoding ("UTF-8");//encoding Format processing//Get file nameString FileName =File.getoriginalfilename (); System.out.println ("FileName:------------------------------------------------------" +fileName); //get File size KBBigDecimal fileSize =NewBigDecimal (File.getsize ()). Divide (NewBigDecimal (1024), 2, BIGDECIMAL.ROUND_HALF_UP); String StartFileName= filename.substring (0, Filename.indexof ("."))); String Endfilename= Filename.substring (Filename.lastindexof ("."))); //New file nameString NewFileName = StartFileName + "_" + math.random () +Endfilename; //File Save pathString Parentpath = Request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload/"; String FilePath= Parentpath +NewFileName; System.out.println ("FilePath:-----------------------------------------------------------" +FilePath); System.out.println ("System.setproperty (' sun.jnu.encoding ')--------" + system.getproperty ("sun.jnu.encoding"))); System.setproperty ("Sun.jnu.encoding", "Utf-8"); System.out.println ("System.setproperty (' sun.jnu.encoding ')--------" + system.getproperty ("sun.jnu.encoding"))); File NewFile=NewFile (Parentpath); if(!newfile.exists ()) {//determine if a folder is created, create a new folder without creating itNewfile.mkdirs (); }        BooleanUploadFile =true; //Compare upload file size to more than 10M        if(Filesize.compareto (NewBigDecimal (1024x768)) > 0) {UploadFile=false; RET= "The size of the uploaded file cannot exceed 10Mb, please re-select!"; }        if(uploadfile) {Try{File.transferto (NewFile (FilePath));//Dump Filesret = "Upload succeeded!"; } Catch(Exception e) {ret= "Upload failed!"; }        }        Try{Response.setcontenttype ("Text/html;charset=utf-8");            Response.getwriter (). write (ret);        Response.getwriter (). Flush (); } Catch(IOException e) {e.printstacktrace (); }    }}

Spring Bean Configuration
    <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver">       <!--maxuploadsize: The maximum file upload value is in bytes -       < Propertyname= "Maxuploadsize"value= "1024000"></ Property>       < Propertyname= "Defaultencoding"value= "GBK"></ Property>      </Bean>

If not configured, the following error may be reported org.springframework.web.bind.MissingServletRequestParameterException:Required Multipartfile Parameter ' file ' is not present

Using spring's multipartfile to implement file upload "original"

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.