In my application I am running an applet to scan a picture from client. I need to upload the scanned file to the server then to database. I can upload the file by submitting a form in JSP, but I need the applet to post the file to URL.
Any hep would be appreciated.
Here is the code:
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/spring/upload");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
connection.setRequestProperty("enctype", "multipart/form-data");
DataOutputStream printout = new DataOutputStream(
connection.getOutputStream());
printout.write(FileUtils.readFileToByteArray(new File("c:\\img_khar.jpg")));
printout.flush();
printout.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
I prefer to use http client from apache for cases like this. They provide a MultipartEntity class that can be added to your HttpPost.
http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html