Upload Files From Java Client to a Java Server

In this mail, you will learn how to code a Java client programme 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 POST request to transfer a file to a server – but that asking's content blazon is not of multipart/form-data, so information technology may not work with the servers which handle multipart request and it requires both customer and server are implemented in Coffee.

To overcome that limitation, in this commodity, nosotros are going to discuss a unlike solution for uploading files from a Java client to any web server in a programmatic manner, without using upload form in HTML lawmaking. Permit'due south examine this interesting solution now.

Code Java multipart utility class:

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

packet cyberspace.codejava.networking;  import java.io.BufferedReader;  import java.io.File; import coffee.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import coffee.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import coffee.net.HttpURLConnection; import java.internet.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List;  /**  * This utility class provides an brainchild layer for sending multipart HTTP  * Mail requests to a spider web server.   * @author world wide web.codejava.net  *  */ public class MultipartUtility { 	private final String boundary; 	private static final String LINE_FEED = "\r\n"; 	private HttpURLConnection httpConn; 	private Cord charset; 	private OutputStream outputStream; 	private PrintWriter writer;  	/** 	 * This constructor initializes a new HTTP Postal service request with content type 	 * is prepare to multipart/form-data 	 * @param requestURL 	 * @param charset 	 * @throws IOException 	 */ 	public MultipartUtility(String requestURL, String charset) 			throws IOException { 		this.charset = charset; 		 		// creates a unique boundary based on fourth dimension postage stamp 		boundary = "===" + System.currentTimeMillis() + "==="; 		 		URL url = new URL(requestURL); 		httpConn = (HttpURLConnection) url.openConnection(); 		httpConn.setUseCaches(false); 		httpConn.setDoOutput(truthful);	// indicates POST method 		httpConn.setDoInput(true); 		httpConn.setRequestProperty("Content-Type", 				"multipart/form-data; boundary=" + purlieus); 		httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); 		httpConn.setRequestProperty("Test", "Bonjour"); 		outputStream = httpConn.getOutputStream(); 		writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), 				true); 	}  	/** 	 * Adds a form field to the request 	 * @param proper noun field name 	 * @param value field value 	 */ 	public void addFormField(Cord name, String value) { 		author.append("--" + boundary).append(LINE_FEED); 		writer.append("Content-Disposition: form-data; proper name=\"" + name + "\"") 				.suspend(LINE_FEED); 		writer.suspend("Content-Type: text/evidently; charset=" + charset).append( 				LINE_FEED); 		writer.suspend(LINE_FEED); 		writer.append(value).append(LINE_FEED); 		writer.affluent(); 	}  	/** 	 * Adds a upload file section to the request  	 * @param fieldName proper name aspect in <input blazon="file" proper 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).append(LINE_FEED); 		writer.append( 				"Content-Disposition: grade-data; name=\"" + fieldName 						+ "\"; filename=\"" + fileName + "\"") 				.suspend(LINE_FEED); 		writer.suspend( 				"Content-Blazon: " 						+ URLConnection.guessContentTypeFromName(fileName)) 				.suspend(LINE_FEED); 		author.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 		author.append(LINE_FEED); 		writer.flush();  		FileInputStream inputStream = new FileInputStream(uploadFile); 		byte[] buffer = new byte[4096]; 		int bytesRead = -1; 		while ((bytesRead = inputStream.read(buffer)) != -one) { 			outputStream.write(buffer, 0, bytesRead); 		} 		outputStream.flush(); 		inputStream.close(); 		 		author.suspend(LINE_FEED); 		author.affluent();		 	}  	/** 	 * Adds a header field to the asking. 	 * @param proper name - name of the header field 	 * @param value - value of the header field 	 */ 	public void addHeaderField(String name, Cord value) { 		author.append(name + ": " + value).append(LINE_FEED); 		author.flush(); 	} 	 	/** 	 * Completes the request and receives response from the server. 	 * @return a listing of Strings as response in case the server returned 	 * status OK, otherwise an exception is thrown. 	 * @throws IOException 	 */ 	public List<Cord> cease() throws IOException { 		List<String> response = new ArrayList<Cord>();  		writer.append(LINE_FEED).flush(); 		writer.append("--" + boundary + "--").append(LINE_FEED); 		writer.close();  		// checks server's status code beginning 		int status = httpConn.getResponseCode(); 		if (status == HttpURLConnection.HTTP_OK) { 			BufferedReader reader = new BufferedReader(new InputStreamReader( 					httpConn.getInputStream())); 			Cord line = nothing; 			while ((line = reader.readLine()) != null) { 				response.add(line); 			} 			reader.close(); 			httpConn.disconnect(); 		} else { 			throw new IOException("Server returned not-OK condition: " + status); 		}  		return response; 	} }

This utility form uses java.net.HttpURLConnection class and follows the RFC 1867 (Class-based File Upload in HTML) to make an HTTP Postal service 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, Cord charset): creates a new example of this grade for a given request URL and charset.
    • void addFormField(String name, String value): adds a regular text field to the asking.
    • void addHeaderField(String name, String value): adds an HTTP header field to the asking.
    • void addFilePart(Cord fieldName, File uploadFile): adhere a file to exist uploaded to the request.
    • List<String> finish(): this method must be invoked lastly to complete the asking and receive response from server as a listing of String.

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

Lawmaking Java Client program to upload file:

Since the MultipartUtility form abstracts all the detailed implementation, a usage example would exist pretty simple every bit shown in the following program:

package net.codejava.networking;  import java.io.File; import java.io.IOException; import java.util.Listing;  /**  * This program demonstrates a usage of the MultipartUtility class.  * @author www.codejava.net  *  */ public class MultipartFileUploader {  	public static void main(String[] args) { 		Cord charset = "UTF-viii"; 		File uploadFile1 = new File("e:/Test/PIC1.JPG"); 		File uploadFile2 = new File("e:/Test/PIC2.JPG"); 		Cord requestURL = "http://localhost:8080/FileUploadSpringMVC/uploadFile.exercise";  		effort { 			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,Spring"); 			 			multipart.addFilePart("fileUpload", uploadFile1); 			multipart.addFilePart("fileUpload", uploadFile2);  			List<String> response = multipart.finish(); 			 			Organization.out.println("SERVER REPLIED:"); 			 			for (String line : response) { 				System.out.println(line); 			} 		} take hold of (IOException ex) { 			System.err.println(ex); 		} 	} }

In this program, we connect to the servlet's URL of the application FileUploadSpringMVC (see this tutorial: Upload files with Leap MVC):

http://localhost:8080/FileUploadSpringMVC/uploadFile.do

Nosotros added 2 header fields, two form fields and 2 upload files under the proper name "fileUpload" – which must match the fields declared in the upload form of the FileUploadSpringMVC application.

When running the higher up program, it will produce the following output:

server response

Nosotros can realize that the server'south response is actually HTML code of the application FileUploadSpringMVC's consequence folio.

And then far in this article, we've discussed nigh how to implement a command line program in Coffee which is capable of upload files to any URL that tin 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.

Related Java File Upload Tutorials:

  • Java Servlet File Upload Example with Servlet 3.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
  • Java Upload files to database (Servlet + JSP + MySQL)
  • Upload Files to Database with Spring MVC and Hide
  • Java FTP file upload tutorial and example

Other Java network tutorials:

  • How to use Java URLConnection and HttpURLConnection
  • Java URLConnection and HttpURLConnection Examples
  • Java HttpURLConnection to download file from an HTTP URL
  • Java HTTP utility class to transport Get/POST asking
  • Coffee Socket Client Examples (TCP/IP)
  • Coffee Socket Server Examples (TCP/IP)
  • How to Create a Conversation Console Awarding in Java using Socket

Most the Author:

Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in honey with Java since and so. Make friend with him on Facebook and sentry his Java videos you YouTube.

Add together comment

beardenmady1938.blogspot.com

Source: https://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

0 Response to "Upload Files From Java Client to a Java Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel