我对HTML的工作原理知之甚少。我想要做的事情与以下类似,但在Android上进行。
<body>
<form action="<%= some_url %>" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Submit">
</form>
</body>
我尝试了以下代码 -
private static void postToUrl(String url_to_upload_on,
String file_name_with_ext, byte[] byteArray) {
String attachmentName = "file";
String attachmentFileName = file_name_with_ext;
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try{
URL url = new URL(url_to_upload_on);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(
connection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
attachmentName + "\";filename=\"" +
attachmentFileName + "\"" + crlf);
request.writeBytes(crlf);
request.write(byteArray);
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary +
twoHyphens + crlf);
request.flush();
request.close();
}catch(Exception e){
e.printStackTrace();
}
}
这个代码没有直接报错,但是当我使用 error-stream 时会出现错误-
Log.w(TAG, "connection.getErrorStream() = " + connection.getErrorStream());
我得到了这个 -
12-14 18:25:54.911: W/uploadToBlobStore(30558): httpUrlConnection.getErrorStream() = com.android.okhttp.internal.http.HttpTransport$FixedLengthInputStream@426dd5a8
尝试了多次,但都没有成功。
PS- 我正在将文件上传到Google Blobstore。
PS- 我无法使用Apache http库或其multipart类,因为Android说它已过时。
编辑1
现在我正在使用以下代码,但仅适用于小于2.3Mb的文件 -
private static void postToUrl3(String url_to_upload_on,
String file_name_with_ext, byte[] byteArray, String mimeType) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(url_to_upload_on);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(byteArray, file_name_with_ext);
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity.build());
httpClient.execute(postRequest);// takes time
} catch (Exception e) {
Log.w("uploadToBlobStore", "postToUrl Exception e = " + e);
e.printStackTrace();
} finally {
if (httpClient != null) {
Log.w("uploadToBlobStore", "connection.closing ");
try {
httpClient.close();
} catch (IOException e) {
Log.w("uploadToBlobStore", "connection.closing errot e = "
+ e);
e.printStackTrace();
}
}
}
}
如何处理更大的文件? PS- 我正在将它发送到 Blobstore,我已经将
maxUploadSizeBytes
和 MaxUploadSizeBytesPerBlob
设置到30MB。我无法解决与大小有关的问题,因为 Google Blobstore 文档说 -
那么它是否可能是 HTTP 连接的问题?如果是,如何配置它。Google 应用引擎包括 Blobstore 服务,该服务允许应用程序提供仅受单个 HTTP 连接上传或下载的数据对象的限制。