Uploading files in Springmvc is more convenient, spring has built-in support classes for uploading files, and does not require complex operations to upload files.
File upload requires two jar support, one is Commons-fileupload.jar and Commons-io.jar. And you need to include a configuration file that supports file uploads in your SPRINGMVC profile:
1 < bean id = "Multipartresolver" class = "Org.springframework.web.multipart.commons.CommonsMultipartResolver" Span style= "color: #0000ff;" >> < property name = "defaultencoding" value =" Utf-8 " /> 3 </ bean >
Configurable items also include Maxuploadsize, Uploadtempdir, Maxinmemorysize, and more.
JSP page code:
1 <Body>2 <formAction= "<%=path%>/upload"Method= "POST"enctype= "Multipart/form-data">3File:<inputtype= "File"name= "File"ID= "File" /><BR/>4Parameters:<inputtype= "text"name= "param"ID= "param" /><BR/>5 <Buttontype= "Submit">Submit</Button>6 </form>7 </Body>
Controller code for File upload:
1 ImportJava.io.File;2 Importjava.io.IOException;3 Importjavax.servlet.http.HttpServletRequest;4 ImportOrg.springframework.stereotype.Controller;5 Importorg.springframework.web.bind.annotation.RequestMapping;6 ImportOrg.springframework.web.bind.annotation.RequestParam;7 ImportOrg.springframework.web.multipart.MultipartFile;8 9 @ControllerTen Public classuploadcontroller{ One A@RequestMapping ("/upload") - PublicString Upload (@RequestParam ("File") multipartfile file, HttpServletRequest request) { - if(File.isempty ()) { theSystem.out.println ("File is null---"); - return NULL; - } - + Try { -String FileName =file.getoriginalfilename (); +FileName =NewString (Filename.getbytes ("iso8859-1"), "UTF-8"); //Prevent Chinese garbled characters in file name, do utf-8 transcoding A atString NewPath = Request.getsession (). Getservletcontext (). Getrealpath ("Upload"); //Use the upload directory under the project to store uploaded files -String param = request.getparameter ("param"); //Get parameters to form submission -System.out.println ("param:" +param); -File NewFile2 =NewFile (NewPath); - if(!newfile2.exists ()) { - Newfile2.mkdir (); in } -File NewFile =NewFile (newpath+file.separator+fileName); to File.transferto (NewFile); //Storage files +}Catch(IOException e) { - e.printstacktrace (); the } * return NULL; $ }Panax Notoginseng}
Springmvc Uploading Files