SPRINGMVC Common Configuration (ii), the most concise configuration to achieve file upload

Source: Internet
Author: User

Spring, Springmvc continuous Introduction, the basic configuration has been introduced in front of a lot, if the small partners are not familiar with this article can be consulted:

1.Spring Basic Configuration
2.Spring Common Configuration
3.Spring Common Configuration (ii)
4.SpringMVC basic configuration (via annotation configuration, non-XML configuration)
5.SpringMVC Common Configuration

OK, then here I would like to say another topic, that is the file upload, I was in the development of Android, the file upload we generally have two strategies, one is through the IO stream upload, but also through the form upload, in fact, these two in the client implementation is very simple, In the service side processing will be slightly different, personal feeling IO upload code is simple, but there are many flawed, or form upload more appropriate. Especially if our daemon is facing both the mobile and the Web front-end, uploading through form is undoubtedly the best solution. OK, nonsense, let's see how to upload a file with one of the simplest configurations possible.
We implement this function mainly by following several steps:

1. Introduction of dependency
2. Create a File Upload page
3. Configure SPRINGMVC
4.WEB Configuration
5. Writing a Controller

OK, follow this step we take a step-by-step look.

Introducing Dependencies

Of course, before we introduce dependencies, we need to create a maven-managed web Project that I don't have to say, and if you're not familiar with it, you can refer to this article SPRINGMVC basic configuration (via annotation configuration, non-XML configuration). After the successful creation, add the following two dependencies on top of the SPRINGMVC framework:

        <dependency>            <groupId>Commons-fileupload</groupId>            <artifactid>Commons-fileupload</artifactid>            <version>1.3.2</version>        </Dependency>        <dependency>            <groupId>Commons-io</groupId>            <artifactid>Commons-io</artifactid>            <version>2.5</version>        </Dependency>

Two dependent libraries, one to solve file upload, a simplified IO operation.

Create a File Upload page

This is a simple JSP page, I create the Views folder in the Resources folder, create a index.jsp file in the Views folder, as follows:

<%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head>    <title>File Upload</title></head><body><form Action="Upload" enctype="Multipart/form-data"  Method="POST">    <input type="file" name="file" />    <input type="Submit" value="Upload" /></form></body></html>

This page is very simple, nothing to say, notice action is upload on the line.

Configure SPRINGMVC

This step is a key step, but there is only one new bean here, let's look at the class first:

@Configuration@EnableWebMvc@ComponentScan("Org.sang") Public  class mvcconfig extends webmvcconfigureradapter{    @Bean     PublicInternalresourceviewresolverViewresolver() {Internalresourceviewresolver viewresolver =NewInternalresourceviewresolver (); Viewresolver.setprefix ("/web-inf/classes/views/"); Viewresolver.setsuffix (". JSP"); Viewresolver.setviewclass (Jstlview.class);returnViewresolver; }@Override     Public void addviewcontrollers(Viewcontrollerregistry Registry) {Registry.addviewcontroller ("/index"). Setviewname ("/index"); }@Bean     PublicMultipartresolverMultipartresolver() {Commonsmultipartresolver resolver =NewCommonsmultipartresolver (); Resolver.setmaxuploadsize (1000000);returnResolver }}

This class has been repeatedly said several times in previous blogs, here is just a multipartresolver method, which is used to provide a multipartresolver bean, This method is mainly based on the business requirements of the Commonsmultipartresolver configuration, I here to limit the upload file size as an example.

Web Configuration

This is also a cliché, the previous several blog also said n many times, do not repeat:

 Public  class webinit implements Webapplicationinitializer {     Public void Onstartup(ServletContext ServletContext)throwsservletexception {Annotationconfigwebapplicationcontext context =NewAnnotationconfigwebapplicationcontext ();        Context.register (Mvcconfig.class);        Context.setservletcontext (ServletContext); Servletregistration.dynamic servlet = Servletcontext.addservlet ("Dispatcher",NewDispatcherservlet (context)); Servlet.addmapping ("/"); Servlet.setloadonstartup (1); }}
Writing a Controller
@Controller Public  class uploadcontroller {    @ResponseBody    @RequestMapping(Value ="/upload", method = Requestmethod.post,produces ="Text/plain;charset=utf-8") PublicStringUpload(Multipartfile file) {Try{Fileutils.writebytearraytofile (NewFile ("/home/sang/workspace/"+file.getoriginalfilename ()), file.getbytes ());return "Upload succeeded"; }Catch(IOException e) {E.printstacktrace ();return "Upload failed"; }    }}

Here, the byte array of the uploaded file is directly written as a file, using the relevant method provided in Common-io.
To run the project at this time, open the index.jsp in the browser, as follows:

Select the file and upload it to see the uploaded file in the/home/sang/workspace directory of your computer.

This case
This case GitHub address

Above.

Resources:
"The creator of Java EE development Spring Boot Combat" chapter fourth

SPRINGMVC Common Configuration (ii), the most concise configuration to achieve 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.