Source Code : Upload files with java
Upload files with java
You'd normally use java.net.URLConnection
to fire HTTP requests. You'd also normally use multipart/form-data
encoding for mixed POST content (binary and character data). Click the link, it
contains information and an example how to compose a multipart/form-data
request body. The specification is in more
detail described in RFC2388.
Here's a kickoff example
String urlToConnect = "http://example.com/upload";
String paramToSend = "fubar";
File fileToUpload = new File("/path/to/file.txt");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"paramToSend\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
writer.println(paramToSend);
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"file.txt\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
Here is how you would do it with Apache HttpClient (this solution is for those who don't mind
using a 3rd party library):
<code>MultipartEntity entity =newMultipartEntity();
entity.addPart("file",newFileBody(file));HttpPost request =newHttpPost(url);
request.setEntity(entity);HttpClient client =newDefaultHttpClient();HttpResponse response = client.execute(request);</code>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
<code>boolean isMultipart =ServletFileUpload.isMultipartContent(request);if(!isMultipart){return;}DiskFileItemFactory factory =newDiskFileItemFactory();
factory.setSizeThreshold(MAX_MEMORY_SIZE);
factory.setRepository(newFile(System.getProperty("java.io.tmpdir")));String uploadFolder = getServletContext().getRealPath("")+File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the serverServletFileUpload upload =newServletFileUpload(factory);
upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size </code>