On File Upload Not Getting Same File Name Java
- Details
- Written by
- Last Updated on xviii July 2019 | Impress Email
In this post, you volition learn how to code a Java client program that upload files to a web server programmatically.
In the commodity Upload file to servlet without using HTML grade,we discussed how to fire an HTTP POST asking to transfer a file to a server – but that asking's content blazon is not of multipart/form-data, so it may not work with the servers which handle multipart request and information technology requires both customer 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 fashion, without using upload form in HTML code. Permit's examine this interesting solution now.
Code Coffee multipart utility grade:
We build the utility class chosen MultipartUtility with the following code:
parcel cyberspace.codejava.networking; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import coffee.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import coffee.internet.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; /** * This utility class provides an abstraction layer for sending multipart HTTP * Mail requests to a spider web server. * @author www.codejava.net * */ public course MultipartUtility { individual concluding Cord boundary; individual static terminal String LINE_FEED = "\r\due north"; private HttpURLConnection httpConn; individual Cord charset; private OutputStream outputStream; private PrintWriter writer; /** * This constructor initializes a new HTTP POST request with content type * is fix to multipart/form-data * @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 purlieus = "===" + Organization.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/class-data; boundary=" + boundary); 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 name field proper name * @param value field value */ public void addFormField(Cord name, String value) { writer.suspend("--" + purlieus).suspend(LINE_FEED); author.suspend("Content-Disposition: form-information; proper name=\"" + proper name + "\"") .append(LINE_FEED); writer.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 noun attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(Cord fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.suspend( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .suspend(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .suspend(LINE_FEED); writer.suspend("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); author.affluent(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -i) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the asking. * @param name - proper name of the header field * @param value - value of the header field */ public void addHeaderField(String proper name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the asking and receives response from the server. * @render a listing of Strings as response in instance the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public List<String> finish() throws IOException { List<Cord> response = new ArrayList<String>(); writer.append(LINE_FEED).flush(); writer.suspend("--" + purlieus + "--").append(LINE_FEED); author.close(); // checks server'south status code first int condition = httpConn.getResponseCode(); if (condition == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != naught) { response.add(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK condition: " + status); } return response; } }
This utility course uses java.internet.HttpURLConnection course and follows the RFC 1867 (Form-based File Upload in HTML) to make an HTTP Mail service asking with multipart/class-data content blazon in order to upload files to a given URL. It has one constructor and iii methods:
-
- MultipartUtility(String requestURL, String charset): creates a new instance of this grade 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 asking.
- void addFilePart(String fieldName, File uploadFile): adhere a file to be uploaded to the asking.
- List<String> finish(): this method must be invoked lastly to complete the request and receive response from server as a listing of Cord.
Now allow's take a look at an example of how to use this utility grade.
Code Java Client program to upload file:
Since the MultipartUtility class abstracts all the detailed implementation, a usage example would be pretty uncomplicated as shown in the following programme:
package net.codejava.networking; import java.io.File; import java.io.IOException; import java.util.List; /** * This plan demonstrates a usage of the MultipartUtility class. * @author world wide web.codejava.net * */ public grade MultipartFileUploader { public static void chief(Cord[] args) { String charset = "UTF-viii"; File uploadFile1 = new File("e:/Examination/PIC1.JPG"); File uploadFile2 = new File("e:/Test/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<String> response = multipart.finish(); System.out.println("SERVER REPLIED:"); for (Cord 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 Spring MVC):
http://localhost:8080/FileUploadSpringMVC/uploadFile.do
We added two header fields, two class fields and 2 upload files under the name "fileUpload" – which must match the fields declared in the upload class of the FileUploadSpringMVC application.
When running the in a higher place program, it will produce the following output:
We can realize that the server's response is really HTML code of the application FileUploadSpringMVC'south result page.
So far in this article, we've discussed about how to implement a control line program in Java which is capable of upload files to whatever URL that can handle multipart request, without implementing an HTML upload course. This would be very useful in example we want to upload files to a spider web server programmatically.
Related Coffee File Upload Tutorials:
- Java Servlet File Upload Example with Servlet 3.0 API
- Spring MVC File Upload Instance
- Struts File Upload Example
- How to Upload File to Java Servlet without using HTML grade
- Java Swing awarding 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 utilise Coffee URLConnection and HttpURLConnection
- Java URLConnection and HttpURLConnection Examples
- Coffee HttpURLConnection to download file from an HTTP URL
- Coffee HTTP utility form to send GET/Mail service request
- Coffee Socket Client Examples (TCP/IP)
- Coffee Socket Server Examples (TCP/IP)
- How to Create a Chat Console Awarding in Java using Socket
About the Author:
Nam Ha Minh is certified Coffee developer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in dearest with Java since so. Brand friend with him on Facebook and sentry his Java videos you YouTube.
Add together comment
Source: https://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
Belum ada Komentar untuk "On File Upload Not Getting Same File Name Java"
Posting Komentar