在Android中读取文件和远程上传时出错

时间:2013-04-12 18:21:40

标签: java android http-post

我的应用程序要求用户选择上传到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的路径。根据日志,我的返回路径是: 文件:///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();
    }
}

如何解决找不到文件的异常?我不知道为什么它不起作用!

1 个答案:

答案 0 :(得分:2)

检查getPath()功能。它可能没有为给定的URI发送正确的路径。