關於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;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM