Spring MVC file upload sample code

As always, record common and easy to forget things. This blog post is mainly about how spring MVC uploads files. The following two upload methods are recorded and recorded for the case. (other spring MVC configurations are omitted)

1. To upload files using spring MVC, you must configure the file parser as follows:

2. Create the upload file form code. Note that the enctype attribute in the form must exist and must be multipart / form data. In addition, when there is a button tag in the form, the face will also be refreshed after submitting the form asynchronously with Ajax. Reason: the form will be submitted again when the button exists, so the page is refreshed.

3.1 use Commons@R_403_613 @Receive uploaded files. Note: in the method Commons@R_403_613 @If the corresponding variable name is not the name of the file input box < input type = "file" style = "display: None" name = "txtfile" id = "uploadfileinput1" accept = "text / plain" > in the corresponding form, you must add @ requestparam ("txtfile") to force injection.

The interface effect diagram is as follows:

3.2. Use commonsmultipartresolver to obtain the stored file object. After obtaining the file object, traverse each file, upload and obtain relevant content.

The first step to get the file parser object should be clear. As long as the corresponding object is configured in the container, we can get it, and it is much more convenient to have a constructor obtained according to the context.

Then judge whether there is a form to upload files according to the request. If not, we will return it directly. Let's see how to judge it in the source code.

Therefore, if request is the request object for uploading files, proceed to step 2. Convert the request into a multi file request object, and then obtain the map where the file is stored.

It is conceivable that this method is less efficient than the first method because it needs to traverse the file map, but it is commonly used in spring MVC.

The renderings are as follows:

Where FileUtils The Java code is as follows:

Of course, to view the entire code, you can access the entire code of my project: https://github.com/YuanFY/blog_demo 。

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>