Spring Upload file

Source: Internet
Author: User

1. configuration file section

Add the following code to the spring configuration file

<class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" ID = "Multipartresolver" />

2. Jar Package Used

Commons-fileupload-1.2.1.jarcommons-io-1.3.2.jar3, the code part--Upload to the local folder
 Public classUploadcontroller {//set the path of the fileFile FilePath =NewFile ("D:/workspace-letter"); @RequestMapping (Value= "/upload", method =requestmethod.post) @ResponseBody//can be successfully transferred     PublicString Upload (@RequestParam multipartfile file)throwsIOException {//get file Original nameString filename =File.getoriginalfilename (); //get file name extensionString fileextension = filename.substring (Filename.lastindexof ("."))); //img filename prefixFile tempfile = File.createtempfile ("img", Fileextension,filepath); Try{InputStream in=File.getinputstream (); OutputStream out=NewFileOutputStream (tempfile);        Ioutils.copy (in, out); }Catch(Exception e) {e.printstacktrace (); }        returnfilename; }}

4. Upload to Server

@Controller Public classUploadcontroller {@RequestMapping (value= "/upload", method =requestmethod.post) @ResponseBody PublicString Upload (@RequestParam multipartfile file, httpservletrequest request)throwsIOException {//set the upload path for the serverFile FilePath =NewFile ("//sharedata//p4"); String filename=File.getoriginalfilename (); String fileextension= Filename.substring (Filename.lastindexof ("."))); File Tempfile= File.createtempfile ("Letter", Fileextension,filepath); Try{InputStream in=File.getinputstream (); OutputStream out=NewFileOutputStream (tempfile);        Ioutils.copy (in, out); } Catch(Exception e) {e.printstacktrace (); }        returnFilepath.getpath () + "/" +filename; }}    

Spring Upload file

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.