dshqd84261 2015-10-06 12:02
浏览 159

使用HttpURLConnection上传多个文件

I want to upload multiple image file to server and below is my code.The code upload only one image to server. I think problem in webservice. Please see the code and help me out please.

 public void uploadMultiFile(ArrayList<String> imgPaths){

        InputStream inputStream = null;
        String result = "";

        URL url = null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "
";
        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 script

This is my php script and i will send unique name if file from android app i didn't understand what to do.

$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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作