下面的代码上传文件到服务器:Android文件上传崩溃问题
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public String uploadFileForStorage(String serverUrl, String filePath) {
StringBuilder responseMsg = new StringBuilder();
try {
final File file = new File(filePath);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
HttpConnectionParams.setConnectionTimeout(httpParameters, UPLOAD_CONNECTION_TIME_OUT);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, UPLOAD_SOCKET_TIME_OUT);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
if (serverUrl.contains("?")) {
serverUrl = Utils.getProperUrlWithOutEncode(serverUrl);
}
HttpPost postRequest = new HttpPost(serverUrl);
FileBody bin = new FileBody(file);
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener() {
@Override
public void transferred(long num) {
total = total + num;
}
});
multipartContent.addPart(CUSTOM_FILE_TAG, bin);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
while ((sResponse = reader.readLine()) != null) {
responseMsg = responseMsg.append(sResponse);
}
} else {
responseMsg = responseMsg.append(String.valueOf(response.getStatusLine().getStatusCode()));
}
} catch (Exception e) {
isError = true;
}
return responseMsg.toString();
}
}
文件正在从平板SD卡上传。 上面的代码可以很好地处理多种Android平板电脑,比如三星Galaxy Note 10.1 & Micromax Funbook 10英寸但在Samsung P6200上传文件时崩溃。崩溃不会立即发生,但会在上传5-10%之后。
此前,上传被三星P6200工作也没关系。我重置了平板电脑的出厂设置,但上传时崩溃仍然存在。此外,OutOfMemoryException不会显示在logcat中。该日志显示它不应该在类文件中的NullPointerException。假设问题是一个HeapSize问题,我该如何处理这个问题。
使用上面的代码,我可以使用SIM(3G/WIFI)与Android平板电脑,如三星Galaxy Note 10.1 & Micromax的Funbook 10
应该加入下面一行从SD卡上传文件高达400 MB代码帮助?
HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
// or any value other than //8192
你可以发布logcat的错误情况?这可能有助于查明错误,但看看http://stackoverflow.com/questions/4455006/posting-a-large-file-in-android无论哪种方式 – Slartibartfast
“日志显示NullPointerException异常的一类文件,它不应该。 ”。你真的需要包含这样的信息。 –
Reuben Scratton:实际上在一个Activity中得到一个NullPointer异常,其中布局只包含一个Button,点击该按钮将启动上传过程。在上传过程成功的情况下,NullPointerException永远不会被抛出。这就是没有在问题中输入细节的原因。我不认为NullPointerException是崩溃的真正原因,否则它会在所有场景中抛出。 – chiranjib