[英]Error in reading file and uploading remotely in Android
我的應用程序要求用戶選擇一個已上傳到PHP腳本的文件。 當用戶選擇文件時,將返回正確的URI,但是當我嘗試訪問文件時,出現FileNotFound錯誤。 以下是onActivityResult代碼:
private static final int FILE_SELECT_CODE = 1234;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d("file upload register page", "File Uri: " + uri.toString());
try {
file_path = FileUtils.getPath(getBaseContext(), uri);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("file upload register page", "File Path: " + file_path);
file = new File(file_path);
UploadFile task = new UploadFile();
task.execute();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
FileUtils.getPath函數返回給定URI的路徑。 根據日志,我返回的路徑是:file:///mnt/sdcard/bluetooth/Tutorial%201.pdf
在AsyncTask UploadFile中,我正在將文件上傳到遠程服務器。 我得到一個錯誤
java.io.FileNotFoundException: /file:/mnt/sdcard/bluetooth/Tutorial%201.pdf (No such file or directory).
這就是我上傳文件的方式:
public void newUpload()
{
HttpEntity resEntity;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response_http = httpclient.execute(httppost);
//Do something with response...
resEntity = response_http.getEntity();
response = EntityUtils.toString(resEntity);
Log.d("response",response);
}
catch (Exception e) {
e.printStackTrace();
}
}
如何解決文件未找到異常? 我不知道為什么它不起作用!
檢查您的getPath()
函數。 它可能沒有為給定的URI發送正確的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.