下面的代碼上傳文件到服務器: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