&& quot;缺少文件&"使用HTTP发布将文件上传到服务器时出错 [英] "Missing file" error while uploading file to server using HTTP post

查看:69
本文介绍了&& quot;缺少文件&"使用HTTP发布将文件上传到服务器时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件从我的android设备上传到服务器.我为此使用以下代码:

I want to upload a file from my android device to a server. I am using the below code for that:

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错误请求,而该错误请求的原因是文件丢失.这是我的logcat输出:

The problem is I am getting a HTTP/1.1 400 Bad Request and the reason for that bad request is Missing File. Here is my logcat output:

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."}

从上面的输出中可以看到该文件存在,但是我不知道为什么不能将其上传到服务器.另外,服务器和url都可以正常工作,因为我已经使用Google Chrome的高级REST客户端"应用程序对其进行了测试.这是该截图.

As you can see from above output that the file exists, but I don't know why can't I upload it to my server. Also the server and url is working absolutely fine as I have already tested it using Google Chrome's "Advanced REST client" app. Here is a screenshot of that.

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

Just an addition to my question, I have also tried the below code I found in many previous answers,

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而崩溃了

But, the above code crashed for me with 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)

有人请帮助我找到我的错误.

Someone Please help me find my error.

提前谢谢!

推荐答案

经过很多努力,我终于解决了我的问题.答案是对我使用apache库的第二种文件上传方式的修改.这是对我有用的代码:

After lot of struggle, I finally solved my problem. The answer is a modification of the second way of file upload where I was using apache libraries. Here is the code that worked for me:

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();
        }

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

The exception I was getting in my question code was

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()语句.为了解决这个问题,我只是把这个功能

One more reason why my app crashed was because I had Toast() statement in my async task. To resolve that I simply put this function

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

,并在我需要敬酒的任何地方称呼它.例如:

and called it wherever I needed to Toast. For example:

showToast("Upload Completed");

我仍然无法弄清楚为什么我的第一个代码不起作用以及为什么它显示缺少文件"错误.关于此的任何其他答案仍将不胜感激.

I still haven't been able to figure out why my first code didn't work and why was it showing "missing file" error. Any more answer regarding that will still be appreciated.

这篇关于&& quot;缺少文件&"使用HTTP发布将文件上传到服务器时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆