为什么我在获取对httpUrlConnection的响应时会得到java.io.FileNotFoundException?

时间:2013-08-14 08:53:56

标签: android httpurlconnection filenotfoundexception datainputstream dataoutputstream

我不知道我是否将我的文件发送到web api。因为没有任何错误给客户请求代码。但是当我得到响应服务器时,它给了我一个java.io.FileNotFoundException。所以我认为我的请求代码中存在错误,因为它没有将任何文件上传到Web服务器,我认为这就是我得到java.io.FileNotFoundException的原因。请帮助我,谢谢。

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    String samplefile = "storage/sdcard0/Pictures/Images/productshot.jpg";
    String urlString = "http://avasd.server.com.ph:1217/api/fileupload";    

        File mFile = new File(samplefile);

        int mychunkSize = 2048 * 1024;
        final long size = mFile.length();
        final long chunks = size < mychunkSize? 1: (mFile.length() / mychunkSize);

        int chunkId = 0;


        int bytesRead, bytesAvailable, bufferSize;

        byte[] buffer;

        int maxBufferSize = 2 * 1024 * 1024;
        try {
            //Client Request

            FileInputStream stream = new FileInputStream(mFile);

            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "-------------------------acebdf13572468";// random data

            String param1 = ""+chunkId;
             String param2 = ""+chunks;
             String param3 = mFile.getName();
             String param4 = samplefile;

            for (chunkId = 0; chunkId < chunks; chunkId++) {

                 URL url = new URL(urlString);

                 // Open a HTTP connection to the URL
                 conn = (HttpURLConnection) url.openConnection();

                 conn.setReadTimeout(20000 /* milliseconds */);
                 conn.setConnectTimeout(20000 /* milliseconds */);


                 // Allow Inputs
                 conn.setDoInput(true);
                 // Allow Outputs
                 conn.setDoOutput(true);
                 // Don't use a cached copy.
                 conn.setUseCaches(false);
                 // Use a post method.
                 conn.setRequestMethod("POST");


                 String encoded = Base64.encodeToString((_username+":"+_password).getBytes(),Base64.NO_WRAP); 
                 conn.setRequestProperty("Authorization", "Basic "+encoded); 
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setChunkedStreamingMode(0);
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                 int length = (int) (param2.length() + param3.length() + mFile.length() + encoded.length() + lineEnd.length() + twoHyphens.length() + boundary.length());   
                 conn.connect();
                 dos = new DataOutputStream( conn.getOutputStream() );
                 dos.writeBytes(twoHyphens + boundary + lineEnd);


                // Send parameter #file
                dos.writeBytes("Content-Disposition: form-data; name=\"fieldNameHere\";filename=\"" + mFile.getName() + "\"" + lineEnd); // filename is the Name of the File to be uploaded
                dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
                dos.writeBytes(lineEnd);


                // Send parameter #chunks
                dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"" + lineEnd);
                dos.writeBytes(param2 + lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);


                // Send parameter #name
                dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd);
                dos.writeBytes(param3 + lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);


                bytesAvailable = stream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // read file and write it into form...
                bytesRead = stream.read(buffer, 0, bufferSize);


                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = stream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = stream.read(buffer, 0, bufferSize);
                    Log.i("BytesAvailable", String.valueOf(bytesAvailable));
                    Log.i("bufferSize", String.valueOf(bufferSize));
                    Log.i("Bytes Read", String.valueOf(bytesRead));
                    Log.i("buffer", String.valueOf(buffer));
                }
                // send multipart form data necesssary after file data...

                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                // close streams

                stream.close();
                dos.flush();
                dos.close();
                Log.i("DOS: ", String.valueOf(dos.size()));


            }

        } catch (MalformedURLException ex) {
            System.out.println("From CLIENT REQUEST:" + ex);
        }catch (IOException ioe) {
            System.out.println("From CLIENT REQUEST:" + ioe);
        }catch (Exception e) {
            Log.e("From CLIENT REQUEST:", e.toString());
        }


        //Server Response
        try {
            System.out.println("Server response is: \n");
            DataInputStream inStream = new DataInputStream(conn.getInputStream());
            String str;
            while ((str = inStream.readLine()) != null) {
            System.out.println(str);
            System.out.println("");
            }
            inStream.close();
            System.out.println("\nEND Server response ");

            } catch (IOException ioex) {
            System.out.println("From (ServerResponse): " + ioex);

            }

2 个答案:

答案 0 :(得分:0)

我认为在将数据写入文件之前,必须确保File变量的父级是可用的。您可以看到以下代码:

/**
 * 
 * @param path
 *            like '/abc/temp' which will retutn '/mnt/sdcard/abc/temp'
 * @return
 */
public static File getFile(String path) {
    File file = new File(Environment.getExternalStorageDirectory() + path);
    File parent = file.getParentFile();
    if (!parent.exists()) {
        parent.mkdirs();
    }
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return file;
}

这是我经常使用的功能。希望它会有所帮助。

答案 1 :(得分:0)

检查manifest.xml中的权限 你应该添加访问sdcard0内存位置的权限: 试试这个