关于android 上传文件

/* 上传文件至Server,uploadUrl:接收文件的处理页面 */

    public String uploadFile(Bitmap src, String uploadUrl, String filename) {

        String end = "\r\n";

        String twoHyphens = "--";

        String boundary = "******";

        try {

            URL url = new URL(uploadUrl);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url

                    .openConnection();

            // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃

            // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。

            httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K

            // 允许输入输出流

            httpURLConnection.setDoInput(true);

            httpURLConnection.setDoOutput(true);

            httpURLConnection.setUseCaches(false);

            // 使用POST方法

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");

            httpURLConnection.setRequestProperty("Charset", "UTF-8");

            httpURLConnection.setRequestProperty("Content-Type",

                    "multipart/form-data;boundary=" + boundary);



            DataOutputStream dos = new DataOutputStream(

                    httpURLConnection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + end);



            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""

                    + filename + "\"" + end);

            dos.writeBytes(end);



            // 将要上传的内容写入流中



            InputStream srcis = Function.Bitmap2IS(src);

            byte[] buffer = new byte[8192]; // 8k

            int count = 0;

            // 读取文件

            while ((count = srcis.read(buffer)) != -1) {

                dos.write(buffer, 0, count);

            }

            srcis.close();



            dos.writeBytes(end);

            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

            dos.flush();



            InputStream is = httpURLConnection.getInputStream();

            InputStreamReader isr = new InputStreamReader(is, "utf-8");

            BufferedReader br = new BufferedReader(isr);

            // 上传返回值

            String sl;

            String result="";

            while((sl = br.readLine()) != null)

            result = result+sl; 

            br.close(); 

            is.close(); 

            return result; 

            //dos.close();

        } catch (Exception e) {

            e.printStackTrace();

            return "网络出错!";

        } 

    }

这是网上的代码,原文地址不记得了,本身是为了解决我自己的一个需求将一个内存中的照片上传,这里有一个问题需要记录一下,以免以后不知道
根据   RFC1867协议

 这里参数的输入方法是

end 为换行\r\n

输入第一行  "Content-Disposition: form-data; name=\"test\""+ end
输入一行空格
输入参数内容
输入定义的分隔符(相当于上面的 twoHyphens + boundary + end)

 

对于接收端,只相当于普通的表单上传而以

 

改过的类



//例子

UpLoadFile uf=new UpLoadFile();



List<UpParameter>upParameters=new ArrayList<UpParameter>();

        UpParameter par=new UpParameter();

        par.name="job_id";

        par.data="123";

        upParameters.add(par);

        

        par=new UpParameter();

        par.name="partner_id";

        par.data="234"; 

        upParameters.add(par);





par=new UpParameter();

        par.name="start_pic";

        par.type=ParType.File;

        par.data=Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/IMG_20120508_171614.jpg"; 

        upParameters.add(par);



 par=new UpParameter();

        par.name="sign_pic";

        par.type=ParType.bytes;

        par.data="000".getBytes(); 

        upParameters.add(par);

 String s= uf.uploadFile( "http://127.0.0.1/ywb/index.php?c=LogsJob&a=addJob",upParameters);



package com.test.uploadtest;



import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.List;



/**

 * 上传文件

 * 

 * @author Administrator

 * 

 */

public class UpLoadFile {

    public static boolean isupok(String result)

    {

        return result.trim().equals("0");

    }  



    /*----------------------------------从返回值中取出文字--------------------*/

    public  String getResultStr(InputStream is)

    {  

        String result="";

        InputStreamReader isr;

        try {

            isr = new InputStreamReader(is, "utf-8");

            BufferedReader br = new BufferedReader(isr);

            // 上传返回值

            String sl; 

            while((sl = br.readLine()) != null)

            result = result+sl; 

            br.close(); 

            is.close();

        } catch (UnsupportedEncodingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }        

        return result; 

    }

    /*-----------------------------------------------------------------------*/

    

    

    /* 上传文件至Server,uploadUrl:接收文件的处理页面 */

    /*本次有两个文件需要上传,所以有点麻烦*/

    public String uploadFile(String uploadUrl,List<UpParameter>upParameters) {

        String end = "\r\n";

        String twoHyphens = "--";

        String boundary = "******";

        String result="";

        try {

            URL url = new URL(uploadUrl);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url

                    .openConnection();

            // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃

            // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。

            httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K

            // 允许输入输出流

            httpURLConnection.setDoInput(true);

            httpURLConnection.setDoOutput(true);

            httpURLConnection.setUseCaches(false);

            // 使用POST方法

            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");

            httpURLConnection.setRequestProperty("Charset", "UTF-8");

            httpURLConnection.setRequestProperty("Content-Type",

                    "multipart/form-data;boundary=" + boundary);



            DataOutputStream dos = new DataOutputStream(

                    httpURLConnection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + end);

            for(UpParameter par:upParameters)

            {

                par.writeTo(dos, twoHyphens + boundary + end, end);

            }

            dos.flush();



            //从返回值中取出值

            result=getResultStr(httpURLConnection.getInputStream());  

        } catch (Exception e) {

            e.printStackTrace();

            result="上传出错.."+e.getMessage();

        }

        return result;

    }

    public enum ParType{Str,File,bytes};

    /***********上传参数类***********/

    public static class UpParameter

    {

        public ParType type=ParType.Str;

        public String name="par";

        public Object data;

        /**

         * @param dos

         * @param boundary  分隔符

         * @param end       结束一般是\r\n

         * @throws IOException

         */

        public void writeTo(DataOutputStream dos,String boundary,String end) throws IOException

        { 

            switch(type)

            {

                case Str:

                    dos.writeBytes("Content-Disposition: form-data; name=\""+name+"\""+ end);

                    dos.writeBytes(end);

                    dos.writeBytes((String) data);

                    dos.writeBytes(end);

                    dos.writeBytes(boundary);

                break;

                case File:

                    String srcPath=(String) data;

                    dos.writeBytes("Content-Disposition: form-data; name=\""+name+"\"; filename=\""

                            + srcPath.substring(srcPath.lastIndexOf("/") + 1)

                            + "\""

                            + end);

                    dos.writeBytes(end);



                    FileInputStream fis = new FileInputStream(srcPath);

                    byte[] buffer = new byte[8192]; // 8k

                    int count = 0;

                    // 读取文件

                    while ((count = fis.read(buffer)) != -1) {

                        dos.write(buffer, 0, count);

                    }

                    fis.close();

                    dos.writeBytes(end);

                    dos.writeBytes(boundary);

                break;

                case bytes: 

                    dos.writeBytes("Content-Disposition: form-data; name=\""+name+"\""+ end);

                    dos.writeBytes(end);

                    dos.write((byte[]) data);

                    dos.writeBytes(end);

                    dos.writeBytes(boundary);

                break;

            }

        }

    }

}

 

你可能感兴趣的:(android)