答案 0 :(得分:0)
我在我的应用中使用了此代码。它的工作。它可能对你有所帮助。
private String doFileUpload() {
final DataOutputStream dos;
String exiting_file_path = filePath;
String boundary = "*****";
String twohypens = "--";
String lineend = "\r\n";
int maxBufferSize = 1 * 1024 * 1024;
int buferSize;
int bytesRead;
String url_string = "your URL";
try {
Log.d("Debug", "Start Uploading");
FileInputStream fileInStream = new FileInputStream(
exiting_file_path);
URL url = new URL(url_string);
httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("POST");
httpUrlConn.setRequestProperty("connection", "Keep-Alive");
httpUrlConn.setRequestProperty("content-type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(httpUrlConn.getOutputStream());
dos.writeBytes(twohypens + boundary + lineend);
dos.writeBytes("content-disposition:form-data; name=\"upload_file\"; filename=\""
+ exiting_file_path + "\"" + lineend);
dos.writeBytes(lineend);
int buferAvailable = fileInStream.available();
buferSize = Math.min(buferAvailable, maxBufferSize);
final byte[] buffer = new byte[buferSize];
bytesRead = fileInStream.read(buffer, 0, buferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, buferSize);
buferAvailable = fileInStream.available();
buferSize = Math.min(buferAvailable, maxBufferSize);
bytesRead = fileInStream.read(buffer, 0, buferSize);
}
dos.writeBytes(lineend);
dos.writeBytes(twohypens + boundary + twohypens + lineend);
fileInStream.close();
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), "" + e, 1).show();
e.printStackTrace();
} catch (MalformedURLException e) {
Toast.makeText(getApplicationContext(), "" + e, 1).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "" + e, 1).show();
e.printStackTrace();
}
try {
DataInputStream inStream = new DataInputStream(
httpUrlConn.getInputStream());
while ((STRRRR = inStream.readLine()) != null) {
Log.d("Debug", "Server Response " + STRRRR);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return STRRRR;
}
答案 1 :(得分:0)
您最有可能使用URL做了一些有趣的事情,比如将其指定为“http://example.com”,服务器会立即将您重定向到“http://example.com/”(请注意结尾处的斜线)重定向代码302。
检查服务器返回的标头,它通常包含正确的位置。