Uploading Files Over Ssh Using Java Code

In this postal service, y'all will learn how to code a Coffee client program that upload files to a web server programmatically.

In the commodity Upload file to servlet without using HTML class,nosotros discussed how to burn down an HTTP Mail service request to transfer a file to a server – merely that request's content type is non of multipart/form-information, 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 article, nosotros are going to hash out 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'south examine this interesting solution now.

Lawmaking Java multipart utility course:

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

package net.codejava.networking;  import java.io.BufferedReader;  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import coffee.io.InputStreamReader; import coffee.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.cyberspace.URL; import coffee.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 web server.   * @author world wide web.codejava.cyberspace  *  */ public form MultipartUtility { 	individual last String purlieus; 	private static final Cord LINE_FEED = "\r\n"; 	private HttpURLConnection httpConn; 	private String charset; 	private OutputStream outputStream; 	private PrintWriter writer;  	/** 	 * This constructor initializes a new HTTP POST request with content blazon 	 * is set to multipart/grade-data 	 * @param requestURL 	 * @param charset 	 * @throws IOException 	 */ 	public MultipartUtility(String requestURL, String charset) 			throws IOException { 		this.charset = charset; 		 		// creates a unique purlieus based on time postage 		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-Blazon", 				"multipart/form-data; purlieus=" + purlieus); 		httpConn.setRequestProperty("User-Amanuensis", "CodeJava Amanuensis"); 		httpConn.setRequestProperty("Test", "Bonjour"); 		outputStream = httpConn.getOutputStream(); 		author = new PrintWriter(new OutputStreamWriter(outputStream, charset), 				true); 	}  	/** 	 * Adds a form field to the request 	 * @param name field proper noun 	 * @param value field value 	 */ 	public void addFormField(String name, String value) { 		writer.suspend("--" + boundary).append(LINE_FEED); 		writer.append("Content-Disposition: form-information; proper name=\"" + name + "\"") 				.append(LINE_FEED); 		writer.append("Content-Blazon: text/evidently; charset=" + charset).append( 				LINE_FEED); 		writer.append(LINE_FEED); 		writer.append(value).suspend(LINE_FEED); 		writer.flush(); 	}  	/** 	 * Adds a upload file section to the request  	 * @param fieldName name attribute in <input blazon="file" name="..." /> 	 * @param uploadFile a File to be uploaded  	 * @throws IOException 	 */ 	public void addFilePart(String fieldName, File uploadFile) 			throws IOException { 		String fileName = uploadFile.getName(); 		author.append("--" + boundary).append(LINE_FEED); 		writer.append( 				"Content-Disposition: form-data; proper noun=\"" + fieldName 						+ "\"; filename=\"" + fileName + "\"") 				.append(LINE_FEED); 		writer.suspend( 				"Content-Type: " 						+ URLConnection.guessContentTypeFromName(fileName)) 				.append(LINE_FEED); 		writer.suspend("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 = -one; 		while ((bytesRead = inputStream.read(buffer)) != -1) { 			outputStream.write(buffer, 0, bytesRead); 		} 		outputStream.flush(); 		inputStream.shut(); 		 		writer.append(LINE_FEED); 		author.flush();		 	}  	/** 	 * Adds a header field to the request. 	 * @param proper noun - proper name of the header field 	 * @param value - value of the header field 	 */ 	public void addHeaderField(Cord name, String value) { 		writer.suspend(name + ": " + value).append(LINE_FEED); 		writer.flush(); 	} 	 	/** 	 * Completes the request and receives response from the server. 	 * @render a list of Strings equally response in case the server returned 	 * condition OK, otherwise an exception is thrown. 	 * @throws IOException 	 */ 	public Listing<String> finish() throws IOException { 		List<String> response = new ArrayList<Cord>();  		writer.suspend(LINE_FEED).affluent(); 		writer.append("--" + boundary + "--").append(LINE_FEED); 		writer.close();  		// checks server's status code outset 		int status = 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 non-OK status: " + status); 		}  		return response; 	} }

This utility course uses java.net.HttpURLConnection class and follows the RFC 1867 (Grade-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(Cord requestURL, String charset): creates a new case of this form for a given request URL and charset.
    • void addFormField(Cord name, String value): adds a regular text field to the request.
    • void addHeaderField(Cord proper noun, String value): adds an HTTP header field to the asking.
    • void addFilePart(String fieldName, File uploadFile): attach a file to exist 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.

At present allow'due south take a expect at an case of how to use this utility class.

Code Java Client program to upload file:

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

package net.codejava.networking;  import coffee.io.File; import java.io.IOException; import coffee.util.List;  /**  * This program demonstrates a usage of the MultipartUtility class.  * @author www.codejava.net  *  */ public form MultipartFileUploader {  	public static void primary(String[] args) { 		String charset = "UTF-8"; 		File uploadFile1 = new File("e:/Test/PIC1.JPG"); 		File uploadFile2 = new File("e:/Test/PIC2.JPG"); 		String requestURL = "http://localhost:8080/FileUploadSpringMVC/uploadFile.practice";  		endeavor { 			MultipartUtility multipart = new MultipartUtility(requestURL, charset); 			 			multipart.addHeaderField("User-Agent", "CodeJava"); 			multipart.addHeaderField("Test-Header", "Header-Value"); 			 			multipart.addFormField("clarification", "Cool Pictures"); 			multipart.addFormField("keywords", "Coffee,upload,Spring"); 			 			multipart.addFilePart("fileUpload", uploadFile1); 			multipart.addFilePart("fileUpload", uploadFile2);  			List<String> response = multipart.finish(); 			 			System.out.println("SERVER REPLIED:"); 			 			for (String line : response) { 				System.out.println(line); 			} 		} catch (IOException ex) { 			System.err.println(ex); 		} 	} }

In this programme, we connect to the servlet'south URL of the application FileUploadSpringMVC (come across this tutorial: Upload files with Bound MVC):

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

We added two header fields, two form fields and 2 upload files nether the name "fileUpload" – which must friction match the fields alleged in the upload class of the FileUploadSpringMVC application.

When running the to a higher place programme, it volition produce the following output:

server response

We tin can realize that the server'southward response is really HTML code of the awarding FileUploadSpringMVC'southward event page.

So far in this commodity, we've discussed about how to implement a control line program in Java which is capable of upload files to any URL that can handle multipart request, without implementing an HTML upload course. This would be very useful in case we want to upload files to a web server programmatically.

Related Coffee File Upload Tutorials:

  • Coffee Servlet File Upload Case with Servlet three.0 API
  • Jump MVC File Upload Example
  • 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 Hibernate
  • Java FTP file upload tutorial and instance

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 form to send Go/POST request
  • Java Socket Customer Examples (TCP/IP)
  • Java Socket Server Examples (TCP/IP)
  • How to Create a Chat Panel Application in Java using Socket

Well-nigh the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

elaminearry1967.blogspot.com

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

0 Response to "Uploading Files Over Ssh Using Java Code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel