我发现以下代码(主要取自Funf)适用于此目的:
public static boolean uploadFile(File file, String uploadurl) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 64 * 1024;
FileInputStream fileInputStream = null;
boolean isSuccess = true;
try {
// ------------------ CLIENT REQUEST
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {}
URL url = new URL(uploadurl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"uploadedfile\";filename=\""
+ file.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
} catch (Exception e) {
isSuccess = false;
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// do something
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
// do something
}
}
}
// ------------------ read the SERVER RESPONSE
try {
if (conn.getResponseCode() != 200) {
isSuccess = false;
}
} catch (IOException e) {
isSuccess = false;
}
return isSuccess;
}