我的应用程序要求用户选择一个上传到 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();
}
}
如何解决文件未找到异常?我不知道为什么它不起作用!