使用HTTP post将文件上传到服务器时出现“丢失文件”错误

时间:2015-04-09 09:11:33

标签: android http file-upload http-post

我想从我的Android设备上传文件到服务器。我正在使用以下代码:

File file = new File("/sdcard/Pictures/","wallpaper.png");        
try {
    Log.i("fileupload","checking file exists="+file.exists());
    Log.i("fileupload","checking file length="+file.length());
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), file.length());        
    reqEntity.setContentType("binary/octet-stream");
    httppost.addHeader("Content-Type", "multipart/form-data");
    reqEntity.setChunked(true);
    httppost.setEntity(reqEntity);
    Log.i("Point1=","We are here");
    HttpResponse response = httpclient.execute(httppost);
    Log.i("Point2=","We are here");
    Log.i("response=",""+response.getStatusLine());
    BufferedReader bufferreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String msg="";
    String line = "";
    while ((line = bufferreader.readLine()) != null) {
        msg += line;
    }
    Log.i("msg=",""+msg);
                    //Do something with response...
    if(response != null) {
        Toast.makeText(getBaseContext(),  "Upload Completed. ", Toast.LENGTH_SHORT).show();

    } else { // Error, no response.
        Toast.makeText(getBaseContext(),  "Server Error. ", Toast.LENGTH_SHORT).show();
    }
} catch (Exception e) {
                    // show error
}

问题是我收到了 HTTP / 1.1 400 Bad Request ,并且该错误请求的原因是Missing File。这是我的logcat输出:

04-09 13:56:06.870      785-866/com.tutsplus.nfcdemo I/fileupload﹕ checking file exists=true
04-09 13:56:06.870      785-866/com.tutsplus.nfcdemo I/fileupload﹕ checking file length=422334
04-09 13:56:06.872      785-866/com.tutsplus.nfcdemo I/Point1=﹕ We are here
04-09 13:56:10.068      785-866/com.tutsplus.nfcdemo I/Point2=﹕ We are here
04-09 13:56:10.068      785-866/com.tutsplus.nfcdemo I/response=﹕ HTTP/1.1 400 Bad Request
04-09 13:56:10.252      785-866/com.tutsplus.nfcdemo I/msg=﹕ {"error":2003,"message":"Missing file."}

正如您从上面的输出中可以看到该文件存在,但我不知道为什么我无法将其上传到我的服务器。 此外,服务器和网址工作正常,因为我已经使用Google Chrome"高级REST客户端"进行了测试。应用程序。这是截图。enter image description here

除了我的问题之外,我还尝试了以前在以前的许多答案中找到的代码,

InputStream inputStream;
try{
    inputStream = new FileInputStream(new File("/sdcard/Pictures/"));
    byte[] data;
    try{
        data = IOUtils.toByteArray(inputStream);
        Log.d("File size", ""+ data.toString());
        MultipartEntityBuilder entityBuilder =   entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),"wallpaper.png")
        entityBuilder.addPart("File",inputStreamBody);
        HttpClient httpClient = new DefaultHttpClient();
        String url="my url";
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        BufferedReader bufferreader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String msg="";
        String line = "";
        while ((line = bufferreader.readLine()) != null) {
            msg += line;
        }
        Log.i("msg=",""+msg);

        // Handle response back from script.
        if(httpResponse != null) {
            Toast.makeText(getBaseContext(),  "Upload Completed. ", Toast.LENGTH_SHORT).show();

        } else { // Error, no response.
            Toast.makeText(getBaseContext(),  "Server Error. ", Toast.LENGTH_SHORT).show();
        }
        } catch (IOException e) {
                e.printStackTrace();
        }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

但是,上面的代码因FileNotFoundException而崩溃了

04-09 16:45:32.876    7694-7750/com.tutsplus.nfcdemo W/System.err﹕ java.io.FileNotFoundException: /sdcard/Pictures: open failed: EISDIR (Is a directory)
04-09 16:45:32.877    7694-7750/com.tutsplus.nfcdemo W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)

有人请帮我找到我的错误。

提前致谢!

2 个答案:

答案 0 :(得分:1)

经过多次斗争,我终于解决了我的问题。答案是修改了我使用apache库的第二种文件上传方式。以下代码对我有用:

InputStream inputStream;
try{
    inputStream = new FileInputStream(new File("/sdcard/Pictures/","wallpaper.png"));
    byte[] data;
    try{
        data = IOUtils.toByteArray(inputStream);
        Log.d("File size", ""+ data.toString());
        MultipartEntityBuilder entityBuilder =   entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data),"wallpaper.png")
        entityBuilder.addPart("File",inputStreamBody);
        HttpClient httpClient = new DefaultHttpClient();
        String url="my url";
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        BufferedReader bufferreader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String msg="";
        String line = "";
        while ((line = bufferreader.readLine()) != null) {
            msg += line;
        }
        Log.i("msg=",""+msg);

        // Handle response back from script.
        if(httpResponse != null) {
            showToast("Upload Completed");

        } else { // Error, no response.
            showToast("Server Error");
        }
        } catch (IOException e) {
                e.printStackTrace();
        }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

我在问题代码中遇到的异常是

04-09 16:45:32.876    7694-7750/com.tutsplus.nfcdemo W/System.err﹕ java.io.FileNotFoundException: /sdcard/Pictures: open failed: EISDIR (Is a directory)
04-09 16:45:32.877    7694-7750/com.tutsplus.nfcdemo W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)

我只是通过

解决了这个问题
inputStream = new FileInputStream(new File("/sdcard/Pictures/","wallpaper.png"));

而不仅仅是这个

inputStream = new FileInputStream(new File("/sdcard/Pictures/"));

我的应用程序崩溃的另一个原因是我的异步任务中有Toast()语句。要解决这个问题,我只需要放置此功能

    public void showToast(final String toast)
    {
        runOnUiThread(new Runnable() {
            public void run()
            {
                    Toast.makeText(FileUpload.this, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

并在我需要Toast的任何地方调用它。例如:

showToast("Upload Completed");

我仍然无法弄清楚为什么我的第一个代码无效,为什么显示“丢失文件”错误。关于这一点的任何更多答案仍将受到赞赏。

答案 1 :(得分:0)

Try This Code:-

String url = "Your image upload url";



        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost postMethod = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity();

        try {


                File file1 = new File("your image path");
                FileBody bin1 = new FileBody(file1, "images/jpeg");

                entity.addPart("images[]", bin1);


            postMethod.setEntity(entity);
            HttpResponse response;
            response = client.execute(postMethod);



            String result = EntityUtils.toString(response.getEntity());

            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS

            String status = jo.getString("status");


                mImageUrlArrayList1.add(imageurl);

                // Log.e("status",status);

            }

        }

        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }