Did anyone upload file to php server by using swing applet before? Need help!!!
Hi,
I need a help. Recently I wrote a swing applet for uploading files to
php server. It seems that everything is fine now. I can get the exactly
same size files in the server. For text file, there is no any problem
to be openned. But for image and moive files (such as .jpeg, .gif .mov
and etc.), those files can not be openned after they are uploaded to
sever even the size is exactly the same as orignal files.
I think that it should be caused by "Content-Type".
For testing, I change my Content-Type to "image/gif" to send gif files.
However, the problem is still there. Now, I have no idea about this
problem. Could any one give me a favor? Thanks in advance!!!
I attached the code related to connection and sending data here for
your review.
public boolean upload() throws Exception{
boolean done = false;
String file_name = file.getName();
String file_data = readFile();
StringBuffer response = new StringBuffer("");
OutputStream os = null;
BufferedReader in = null;
HttpURLConnection conn = null;
try{
URL serverURL = new URL(url);
// connect to server
URLConnection uc = serverURL.openConnection();
conn = (HttpURLConnection) uc;
conn.setAllowUserInteraction(true);
conn.setInstanceFollowRedirects(true);
// set connection as POST
conn.setRequestMethod("POST");
conn.setDoOutput(true); // turns it into a post
// setup headers
conn.setRequestProperty(
"Content-Type",
"multipart/form-data; boundary=" + CONTENT_BOUNDARY);
conn.setRequestProperty("Accept-Language", "en-us");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("CACHE-CONTROL", "no-cache");
os = conn.getOutputStream();
String request =
"--"
+ CONTENT_BOUNDARY
+ "\r\n"
+ "Content-Disposition: form-data; name=\"upfile\"\r\n\r\n"
+ file_name
+ "\r\n"
+ "--"
+ CONTENT_BOUNDARY
+ "\r\n"
+ "Content-Disposition: form-data; name=\"upfile\"; filename=" +
file_name
+ "\r\nContent-Type: multipart/form-data\r\n\r\n"
+ file_data //file is read into a string here, is it OK? But no
other choose.
+ "\r\n"
+ "--"
+ CONTENT_BOUNDARY
+ "\r\n";
System.out.println("DEBUG: Sending the following request:\n\r" +
request);
System.out.println("DEBUG: Sending the post request...\n\r");
os.flush();
os.write(request.getBytes(), 0, request.getBytes().length);
os.flush();
in = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// closing connections
in.close();
in = null;
os.close();
os = null;
conn.disconnect();
conn = null;
done = true;