使用HttpURLConnection上传多个文件

时间:2015-10-06 12:02:54

标签: php android

我想将多个图像文件上传到服务器,下面是我的代码。代码只将一个图像上传到服务器。我认为webservice中存在问题。 请查看代码并帮助我。

 public void uploadMultiFile(ArrayList<String> imgPaths){

        InputStream inputStream = null;
        String result = "";

        URL url = null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int maxBufferSize = 1 * 1024 * 1024;
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        ArrayList<String> filenames = new ArrayList<String>();

        int serverResponseCode = 0;

        FileInputStream fileInputStream;

        File sourceFile[] = new File[imgPaths.size()];
        for (int i=0;i<imgPaths.size();i++){
            sourceFile[i] = new File(imgPaths.get(i));
           // Toast.makeText(getApplicationContext(),imgPaths.get(i),Toast.LENGTH_SHORT).show();
        }

        try {
            url = new URL("url");
            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            //filename set
            for (int i=0;i<imgPaths.size();i++){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
                String ext = sourceFile[i].getName().substring(sourceFile[i].getName().lastIndexOf(".") + 1);
                String format = simpleDateFormat.format(new Date()) + i+"."+ext;
                filenames.add(format);
            }

            for (int i=0;i<filenames.size(); i++) {
                conn.setRequestProperty("uploaded_file"+i, filenames.get(i));
                   // Toast.makeText(getApplicationContext(),filenames.get(i),Toast.LENGTH_SHORT).show();
            }
            conn.setRequestProperty("filesname", "simple");
            for (int i=0;i<filenames.size(); i++) {
                if(i == 0){
                    fileInputStream = new FileInputStream(sourceFile[i]);

                    dos = new DataOutputStream(conn.getOutputStream());
                    String fnm = filenames.get(i);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    String fname = "uploaded_file" + i;
                    dos.writeBytes("Content-Disposition: form-data; name=\"" + fname + "\";filename=\""
                            + filenames.get(i) + "\"" + lineEnd);

                    dos.writeBytes(lineEnd);

                    // create a buffer of  maximum size
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

                }else{
                    if(i >= 1) {
                        FileInputStream fileInputStream1 = new FileInputStream(sourceFile[i]);

                        dos.writeBytes(lineEnd);
                        dos.flush();
                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        String fname = "uploaded_file" + i;
                        dos.writeBytes("Content-Disposition: form-data; name=\"" + fname + "\";filename=\""
                                + filenames.get(i) + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                        // create a buffer of  maximum size
                        bytesAvailable = fileInputStream1.available();

                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fileInputStream1.read(buffer, 0, bufferSize);

                        while (bytesRead > 0) {
                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream1.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream1.read(buffer, 0, bufferSize);
                        }
                        fileInputStream1.close();
                    }
                }
            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            final String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {
                inputStream = conn.getInputStream();
                result = this.convertStreamToString(inputStream);
            }


        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Error",e.getMessage());
        }

    }
  

Php脚本

这是我的PHP脚本,如果来自Android应用程序的文件,我将发送唯一的名称,我不知道该怎么做。

$return_arr=array();
    $Id=$_GET['count'];
    $CurrentDate=time();
    $total_files = count($_FILES);
    $cnt = 0;   
    for ($x = 1; $x <= $total_files; $x++) {
        $cnt = 0;
        $param = "uploaded_file".$cnt;

        if(isset($_FILES[$param]['name'][$x]) && $_FILES[$param]['name'][$x]!='')
        {

            $file_path = "../post_uploaded_images/";

            $file_path = $file_path . basename( $CurrentDate ."_". $_FILES[$param]['name'][$x]);
            if(@move_uploaded_file($_FILES[$param]['tmp_name'][$x], $file_path)) 
            {
               echo "success";

            } else{

                echo "fail";
            }           
        }
        $cnt = $cnt + 1;
    }

0 个答案:

没有答案