您的位置:首页 > 产品设计 > UI/UE

Upload files by sending multipart request programmatically

2017-02-08 07:45 567 查看
In the article
Upload file to servlet without using HTML form,
we discussed how to fire an HTTP POST request to transfer a file to a server – but that request’s content type is not of

multipart/form-data, so it may not work with the servers which handle multipart request and it requires both client and server are implemented in Java. To overcome that limitation, in this article, we are going to discuss a different solution for uploading
files from a Java client to any web server in a programmatic way, without using upload form in HTML code. Let’s examine this interesting solution now.  

Coding multipart utility class

We build the utility class called
MultipartUtility with the following code:

  This utility class uses
java.net.HttpURLConnection class and follows the
RFC 1867 (Form-based File Upload in HTML) to make an HTTP POST request with

multipart/form-data content type in order to upload files to a given URL. It has one constructor and three methods:

MultipartUtility(String requestURL, String charset): creates a new instance of this class for a given request URL and charset.
void
addFormField(String name, String value): adds a regular text field to the request.
void
addHeaderField(String name, String value): adds an HTTP header field to the request.
void
addFilePart(String fieldName, File uploadFile): attach a file to be uploaded to the request.
List<String>
finish(): this method must be invoked lastly to complete the request and receive response from server as a list of String.

Now let’s take a look at an example of how to use this utility class.  

Coding a test program

Since the
MultipartUtility class abstracts all the detailed implementation, a usage example would be pretty simple as shown in the following program:

In this program, we connect to the servlet’s URL of the application FileUploadSpringMVC (see this tutorial:

Upload files with Spring MVC):
http://localhost:8080/FileUploadSpringMVC/uploadFile.do We added two header fields, two form fields and two upload files under the name “fileUpload” – which must match the fields declared in the

upload form of the FileUploadSpringMVC application. When running the above program, it will produce the following output:


We can realize that the server’s response is actually
HTML code of the application FileUploadSpringMVC’s
result page. So far in this article, we’ve discussed about how to implement a command line program in Java which is capable of upload files to any URL that can handle multipart request, without implementing an HTML upload form. This would be very useful
in case we want to upload files to a web server programmatically.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java upload
相关文章推荐