How to Handle Multipart File Upload in Java
- Details
- Written past
- Terminal Updated on eighteen July 2019 | Print E-mail
In this post, you will learn how to lawmaking a Java client program that upload files to a web server programmatically.
In the article Upload file to servlet without using HTML form,we discussed how to fire an HTTP Postal service request to transfer a file to a server – merely that asking's content type is not of multipart/class-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 customer to any web server in a programmatic manner, without using upload course in HTML code. Let's examine this interesting solution now.
Lawmaking Java multipart utility grade:
We build the utility course called MultipartUtility with the following code:
parcel net.codejava.networking; import java.io.BufferedReader; import java.io.File; import coffee.io.FileInputStream; import coffee.io.IOException; import coffee.io.InputStreamReader; import java.io.OutputStream; import coffee.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; /** * This utility class provides an brainchild layer for sending multipart HTTP * POST requests to a spider web server. * @author world wide web.codejava.net * */ public class MultipartUtility { individual final String purlieus; private static last String LINE_FEED = "\r\due north"; private HttpURLConnection httpConn; private Cord charset; private OutputStream outputStream; individual PrintWriter writer; /** * This constructor initializes a new HTTP Mail request with content type * is set to multipart/form-information * @param requestURL * @param charset * @throws IOException */ public MultipartUtility(String requestURL, Cord charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates Mail service method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/grade-data; boundary=" + boundary); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Exam", "Bonjour"); outputStream = httpConn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), truthful); } /** * Adds a form field to the request * @param name field name * @param value field value */ public void addFormField(String proper noun, String value) { writer.append("--" + purlieus).append(LINE_FEED); writer.append("Content-Disposition: course-data; name=\"" + name + "\"") .append(LINE_FEED); author.append("Content-Type: text/plain; charset=" + charset).append( LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } /** * Adds a upload file section to the request * @param fieldName proper name aspect in <input type="file" name="..." /> * @param uploadFile a File to exist uploaded * @throws IOException */ public void addFilePart(Cord fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).suspend(LINE_FEED); writer.suspend( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .suspend(LINE_FEED); writer.suspend( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); author.append("Content-Transfer-Encoding: binary").suspend(LINE_FEED); writer.append(LINE_FEED); writer.affluent(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -one; while ((bytesRead = inputStream.read(buffer)) != -i) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.shut(); author.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(String proper noun, String value) { writer.append(proper name + ": " + value).append(LINE_FEED); author.flush(); } /** * Completes the request and receives response from the server. * @render a list of Strings as response in instance the server returned * condition OK, otherwise an exception is thrown. * @throws IOException */ public Listing<Cord> stop() throws IOException { List<String> response = new ArrayList<Cord>(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); author.shut(); // checks server's condition code showtime int condition = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned not-OK condition: " + condition); } return response; } }
This utility class uses coffee.net.HttpURLConnection grade and follows the RFC 1867 (Form-based File Upload in HTML) to make an HTTP POST request with multipart/form-information content type in club to upload files to a given URL. It has 1 constructor and three methods:
-
- MultipartUtility(String requestURL, Cord charset): creates a new example of this class for a given request URL and charset.
- void addFormField(String proper name, Cord value): adds a regular text field to the request.
- void addHeaderField(Cord 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.
- Listing<String> terminate(): this method must exist invoked lastly to complete the asking and receive response from server as a listing of Cord.
Now let'south take a look at an case of how to apply this utility class.
Code Coffee Client program to upload file:
Since the MultipartUtility class abstracts all the detailed implementation, a usage example would be pretty simple equally shown in the following programme:
parcel cyberspace.codejava.networking; import coffee.io.File; import coffee.io.IOException; import coffee.util.List; /** * This plan demonstrates a usage of the MultipartUtility grade. * @author www.codejava.internet * */ public form MultipartFileUploader { public static void principal(String[] args) { String charset = "UTF-8"; File uploadFile1 = new File("e:/Test/PIC1.JPG"); File uploadFile2 = new File("e:/Exam/PIC2.JPG"); Cord requestURL = "http://localhost:8080/FileUploadSpringMVC/uploadFile.do"; try { MultipartUtility multipart = new MultipartUtility(requestURL, charset); multipart.addHeaderField("User-Agent", "CodeJava"); multipart.addHeaderField("Test-Header", "Header-Value"); multipart.addFormField("description", "Cool Pictures"); multipart.addFormField("keywords", "Java,upload,Jump"); multipart.addFilePart("fileUpload", uploadFile1); multipart.addFilePart("fileUpload", uploadFile2); List<Cord> response = multipart.finish(); Organisation.out.println("SERVER REPLIED:"); for (String line : response) { System.out.println(line); } } catch (IOException ex) { System.err.println(ex); } } }
In this program, nosotros connect to the servlet's URL of the awarding FileUploadSpringMVC (see this tutorial: Upload files with Spring MVC):
http://localhost:8080/FileUploadSpringMVC/uploadFile.exercise
We added two header fields, two class fields and two upload files under the name "fileUpload" – which must lucifer the fields declared in the upload grade of the FileUploadSpringMVC application.
When running the to a higher place programme, it will produce the following output:
We can realize that the server'south response is really HTML code of the application FileUploadSpringMVC's result page.
So far in this article, nosotros've discussed well-nigh how to implement a control line program in Java which is capable of upload files to any URL that tin can handle multipart asking, without implementing an HTML upload form. This would be very useful in case we desire to upload files to a spider web server programmatically.
Related Java File Upload Tutorials:
- Java Servlet File Upload Case with Servlet iii.0 API
- Spring MVC File Upload Case
- Struts File Upload Example
- How to Upload File to Java Servlet without using HTML form
- Java Swing application to upload files to HTTP server with progress bar
- Coffee Upload files to database (Servlet + JSP + MySQL)
- Upload Files to Database with Spring MVC and Hide
- Coffee FTP file upload tutorial and example
Other Java network tutorials:
- How to apply Java URLConnection and HttpURLConnection
- Java URLConnection and HttpURLConnection Examples
- Java HttpURLConnection to download file from an HTTP URL
- Java HTTP utility class to send GET/Postal service request
- Java Socket Client Examples (TCP/IP)
- Coffee Socket Server Examples (TCP/IP)
- How to Create a Conversation Panel Awarding in Java using Socket
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java 1.iv and has been falling in love with Java since and then. Brand friend with him on Facebook and sentry his Coffee videos you YouTube.
Add comment
Source: https://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
0 Response to "How to Handle Multipart File Upload in Java"
Enviar um comentário