I am not completely sure if this is possible, but I would like to upload a file to a website of which I have created. I would like to upload this file, by only using Java and no real personal help. By this I mean a user would be able to click the application and then the application would do the rest.
So lets say I have a variable with the file like so final static File file = new File (”file.txt”);
and then in some way connect to a website like http://example.com/
which would then have a form to upload files to. The code would then upload the file.txt
to the form and submit it.
In theory it seems possible, but I am not completely sure where to start and whether there are any Jar libraries or already written codes, which could possibly help. If this is not possible I would like to know if there are any other possible way, which could achieve the same thing in another way.
-
1What does "no real personal help" mean? – chrylis -cautiouslyoptimistic- Dec 14 '16 at 22:36
-
@chrylis I appreciate the question, I just mean that it should be able to run by itself by one click. The user should not have to click multiple things to upload one file, just one click and the app would do the rest. – Dec 14 '16 at 22:43
-
Are you writing the backend as well? – chrylis -cautiouslyoptimistic- Dec 14 '16 at 22:45
-
@chrylis If you mean the website, form and submit (PHP) then yes. – Dec 14 '16 at 23:00
4 Answers
This link might be useful to you: http://commons.apache.org/proper/commons-fileupload/
The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.

- 21
- 4
-
I appreciate the feedback, I actually did not know the commons.apache package had file upload packages. – Dec 15 '16 at 00:00
This can be accomplished more easily by using Apache HttpComponents. I'd advise using it, because Java's http client is not very good. If you don't want to use a 3rd party library, you can find a more complicated and less robust version on this post. Here's a sample using Apache HttpComponents:
public String uploadFile(String url, String paramater, File file)
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart(parameter, cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
String response = response.getStatusLine();
httpclient.getConnectionManager().shutdown();
return response;
}
Where String url
is the URL to upload the file to, String parameter
is the parameter name for the http post request, and File file
is the file to upload.

- 1
- 1

- 1,083
- 3
- 15
- 31
-
1I really appreciate the feedback, I will try it out and see if it works and get back. – Dec 14 '16 at 23:59
-
@fkrottenkirk Sure! Ah, my fault! I just realized I set it `void`, but it should return a String. Updated the answer. – Aaron Esau Dec 15 '16 at 00:02
-
I have imported the package and code, when declaring url, parameter and file I should just do it outside of the function or how? Also a great part of the code has stripes over it. – Dec 15 '16 at 00:23
-
@fkrottenkirk Ok. So now, to upload a file, you run `uploadFile("http://example.com/uploadfile.php", "file", file)` and change the fields to match your needs. The parameter is the POST parameter the contains the file. I don't know what your application set it to, though. I don't know about the green stripes, but here's the function (on another source in hope to evade the green thing) https://gist.github.com/Arinerron/1fc812f62d4679c70eae85682ff4607d – Aaron Esau Dec 15 '16 at 00:49
-
1okay so currently my code looks like in this link http://pastebin.com/85Fw0Gtn I have commented out where the errors are and what they are. – Dec 15 '16 at 03:49
Try it: STEP1: created and interface for events.
public interface IHTTPMultipart {
public void OnFileUploading(String fileName, long uploading, long filesize, float porcent);
public void OnFileUploaded(String fileName);
public void OnAllFilesUploaded();
public void OnDataReceived(byte[] content);
public void OnError(int codeError);
public void OnDownloadingData(long received, long max, float porcent);
}
Step 2: Created a class uploader a files that implements IHTTPMultipart
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author Owner
*/
public class HTTPMultipart implements Runnable {
private final String boundary = "===" + System.currentTimeMillis() + "===";
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset = "uft-8";
private final HashMap<String, String> variables = new HashMap<String, String>();
private final HashMap<String, File> files = new HashMap<String, File>();
private final String url;
private Thread th1 = null;
private IHTTPMultipart event = null;
private int buffer = 4096;
private int responseCode = -1;
private byte[] responseData = null;
private int timeOut = 120000;
HTTPMultipart(String url) {
this.url = url;
}
public void setEvent(IHTTPMultipart event) {
this.event = event;
}
public void setBuffer(int buffer) {
this.buffer = buffer;
}
public void setEncode(String enc) {
this.charset = enc;
}
public void addVariable(String key, String value) {
if (!variables.containsKey(key)) {
variables.put(key, value);
}
}
public void addFile(String key, File file) {
if (!files.containsKey(key)) {
files.put(key, file);
}
}
public void addFile(String key, String file) {
if (!files.containsKey(key)) {
files.put(key, new File(file));
}
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public int getResponseCode() {
return this.responseCode;
}
public byte[] getResponseData() {
return this.responseData;
}
public void send() {
th1 = new Thread(this);
th1.start();
}
@Override
public void run() {
try {
URL url1 = new URL(this.url);
httpConn = (HttpURLConnection) url1.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
if (this.timeOut>0){
httpConn.setConnectTimeout(this.timeOut);
}
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
StringBuilder str = new StringBuilder();
//Read all variables.
Iterator it = this.variables.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
str.append("--").append(boundary).append(LINE_FEED);
str.append("Content-Disposition: form-data; name=\"").append(String.valueOf(pairs.getKey())).append("\"")
.append(LINE_FEED);
str.append("Content-Type: text/plain; charset=").append(charset).append(
LINE_FEED);
str.append(LINE_FEED);
str.append(String.valueOf(pairs.getValue())).append(LINE_FEED);
}
OutputStream os = httpConn.getOutputStream();
os.write(str.toString().getBytes());
it = this.files.entrySet().iterator();
while (it.hasNext()) {
str = new StringBuilder();
Map.Entry pairs = (Map.Entry) it.next();
File file = (File) pairs.getValue();
String fieldName = String.valueOf(pairs.getKey());
String fileName = file.getName();
str.append("--").append(boundary).append(LINE_FEED);
str.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"")
.append(LINE_FEED);
str.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
str.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
str.append(LINE_FEED);
os.write(str.toString().getBytes());
FileInputStream inputStream = new FileInputStream(file);
byte[] buff = new byte[buffer];
int bytesRead;
long fileSize = file.length();
long uploading = 0;
while ((bytesRead = inputStream.read(buff)) != -1) {
os.write(buff, 0, bytesRead);
uploading += bytesRead;
if (event != null) {
float porcent = (uploading * 100) / fileSize;
event.OnFileUploading(fileName, uploading, fileSize, porcent);
}
}
inputStream.close();
if (event != null) {
event.OnFileUploading(fileName, fileSize, fileSize, 100f);
event.OnFileUploaded(fileName);
}
}
try {
os.flush();
} catch (Exception e) {
}
os.close();
if (event != null) {
event.OnAllFilesUploaded();
}
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis2 = new BufferedInputStream(httpConn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
long maxSize = httpConn.getContentLengthLong();
long received = 0l;
byte[] buf = new byte[buffer];
int bytesRead = -1;
while ((bytesRead = bis2.read(buf)) != -1) {
bos.write(buf, 0, bytesRead);
received += bytesRead;
if (event != null) {
float porcent = (received * 100) / maxSize;
event.OnDownloadingData(received, maxSize, porcent);
}
}
bis2.close();
bos.close();
this.responseCode = 0;
this.responseData = bos.toByteArray();
if (event != null) {
this.event.OnDataReceived(this.responseData);
}
} else {
this.responseCode = 998;
this.responseData = (httpConn.getResponseCode() + "").getBytes();
if (event != null) {
this.event.OnError(httpConn.getResponseCode());
}
}
} catch (Exception e) {
this.responseCode = 999;
this.responseData = e.getMessage().getBytes();
if (event != null) {
event.OnError(999);
}
}
}
}
STEP 3: TEST THE CODE.
String url = "add here your url http";
HTTPMultipart upload = new HTTPMultipart(url);
File file = new File("add here your file dir");
String variableName = "myFile";
//Add one file or more files.
upload.addFile(variableName, file);
//Add variable example
upload.addVariable("var1", "hello");
//Set the asyncronic events.
upload.setEvent(new Net.HTTP.IHTTPMultipart() {
@Override
public void OnFileUploading(String fileName, long uploading, long filesize, float porcent) {
}
@Override
public void OnFileUploaded(String fileName) {
}
@Override
public void OnAllFilesUploaded() {
}
@Override
public void OnDataReceived(byte[] content) {
}
@Override
public void OnError(int codeError) {
}
@Override
public void OnDownloadingData(long received, long max, float porcent) {
}
});
upload.send();

- 1,180
- 2
- 13
- 30
-
I really appreciate the answer, there are quite a load of things going on. I can see you have added where I have to change, the URL and the file, but shouldn't there also be a place where I enter what the form or file upload field is called? – Dec 15 '16 at 03:08
-
yes. you can use the mehod example: addVariable("key", "value") example for this example upload.addVariable("var1", "hello"); – toto Dec 15 '16 at 04:21
My suggestion : use Asynchronous Http Client from com.ning.http.client.
version in the example below :
<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.9.31</version>
</dependency>
Code Example :
package url;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Response;
import com.ning.http.client.multipart.FilePart;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
public class Upload {
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
String url = "http://...";
FilePart file = new FilePart("file", new File("c:/tmp/014.csv"), "text/csv", StandardCharsets.UTF_8, "014.csv");
AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
try (AsyncHttpClient httpClient = new AsyncHttpClient(builder.build())) {
AsyncHttpClient.BoundRequestBuilder requestBuilder = httpClient.preparePost(url).addBodyPart(file);
requestBuilder.addHeader("Content-Type", "multipart/form-data");
Response response = requestBuilder.execute().get();
int status = response.getStatusCode();
String body = response.getResponseBody();
System.out.println(status + "|" + body + "|");
}
}
}
You do not have to use MultipartBody or MultipartUtils classes.
From this code, the request body will be :
--6wlOhAzOFwLqU5b1acdqVfknDfLVJwj4o5OAvhk
Content-Disposition: form-data; name="file"; filename="014.csv"
Content-Type: text/csv; charset=UTF-8
Content-Transfer-Encoding: binary
014;csv
--6wlOhAzOFwLqU5b1acdqVfknDfLVJwj4o5OAvhk--
where '014;csv' is the content of the file named 014.csv.
The headers are :
content-length=238
content-type=multipart/form-data; boundary=6wlOhAzOFwLqU5b1acdqVfknDfLVJwj4o5OAvhk
connection=keep-alive
host=localhost:8580
accept=*/*
user-agent=AHC/1.0
Note that the physical name of the file is not transmitted, only the file name passed as last argument of FilePart constructor.

- 39
- 2