Android通过HttpURLConnection上传多个文件至服务器 - 流传输

上传单个文件:

    public static void uploadFile(final File file, final String url, final Handler handler, final HttpCallbackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
                String PREFIX = "--" , LINE_END = "\r\n";
                String CONTENT_TYPE = "multipart/form-data"; //内容类型
                try {
                    URL httpUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    conn.setDoInput(true); //允许输入流
                    conn.setDoOutput(true); //允许输出流
                    conn.setUseCaches(false); //不允许使用缓存
                    conn.setRequestMethod("POST"); //请求方式
                    conn.setRequestProperty("Charset", "UTF-8");
                    //设置编码
                    conn.setRequestProperty("connection", "keep-alive");
                    conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
                    if(file!=null) {
                        OutputStream outputSteam=conn.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(outputSteam);
                        StringBuffer sb = new StringBuffer();
                        sb.append(PREFIX);
                        sb.append(BOUNDARY);
                        sb.append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName()+"\""+LINE_END);
                        sb.append("Content-Type: application/octet-stream; charset="+ "UTF-8" +LINE_END);
                        sb.append(LINE_END);
                        dos.write(sb.toString().getBytes());
 
 
                        InputStream is = new FileInputStream(file);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while((len=is.read(bytes))!=-1) {
                            dos.write(bytes, 0, len);
                        }
                        is.close();
                        dos.write(LINE_END.getBytes());
                        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                        dos.write(end_data);
                        dos.flush();
                        /**
                         * 获取响应码 200=成功
                         * 当响应成功,获取响应的流
                         */
                        int res = conn.getResponseCode();
                        //  Log.e(TAG, "response code:"+res);
                        if(res==200){
                            listener.onFinish(res);
                        }
                    }
                } catch (MalformedURLException e)
                { e.printStackTrace(); }
                catch (IOException e)
                { e.printStackTrace(); }
                return;
            }
        }).start();
    }

上传多个文件:

public static void uploadFile(final List files, final String url, final Handler handler, final HttpCallbackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
                String PREFIX = "--" , LINE_END = "\r\n";
                String CONTENT_TYPE = "multipart/form-data"; //内容类型
                try {
                    URL httpUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    conn.setDoInput(true); //允许输入流
                    conn.setDoOutput(true); //允许输出流
                    conn.setUseCaches(false); //不允许使用缓存
                    conn.setRequestMethod("POST"); //请求方式
                    conn.setRequestProperty("Charset", "UTF-8");
                    //设置编码
                    conn.setRequestProperty("connection", "keep-alive");
                    conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
               //     if(files.size()!= 0) {
                        /** * 当文件不为空,把文件包装并且上传 */
                        OutputStream outputSteam=conn.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(outputSteam);
                        for(int i = 0; i < files.size(); i++){
                            StringBuffer sb = new StringBuffer();
                            sb.append(PREFIX);
                            sb.append(BOUNDARY);
                            sb.append(LINE_END);
                            sb.append("Content-Disposition: form-data; name=\"img" + i + "\"; filename=\"" + files.get(i).getName()+"\""+LINE_END);
                            //sb.append("Content-Type: application/octet-stream; charset="+ "UTF-8" +LINE_END);
                            sb.append(LINE_END);
                            dos.write(sb.toString().getBytes());
                            InputStream is = new FileInputStream(files.get(i));
                            byte[] bytes = new byte[1024];
                            int len = -1;
                            while((len=is.read(bytes))!=-1) {
                                dos.write(bytes, 0, len);
                            }
 
                            dos.write(LINE_END.getBytes());
                            is.close();
 
                     }
                        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                        dos.write(end_data);
                        dos.flush();
                        /**
                         * 获取响应码 200=成功
                         * 当响应成功,获取响应的流
                         */
                        int res = conn.getResponseCode();
                        //  Log.e(TAG, "response code:"+res);
                        if(res==200){
                            listener.onFinish(res);
                        }
 
                } catch (MalformedURLException e)
                { e.printStackTrace(); }
                catch (IOException e)
                { e.printStackTrace(); }
                return;
            }
        }).start();
    }

注意填写字节流的时候与单张图片的区别。

你可能感兴趣的:(【,Android,工具封装,】,Android,上传文件)