Android 文件上傳

2023-03-31 14:16 更新

本節(jié)引言

本節(jié)和下一節(jié)文件下載一樣,慎入...現(xiàn)在實(shí)際開發(fā)涉及文件上傳不會(huì)自己寫上傳代碼,一般 會(huì)集成第三網(wǎng)絡(luò)庫(kù)來(lái)做圖片上傳,比如android-async-http,okhttp等,另外還有七牛也提供 了下載和上傳的API,喜歡的可以去官網(wǎng)查看相關(guān)的API文檔!本節(jié)的話有興趣看看就好! 


1.項(xiàng)目用到的圖片上傳的關(guān)鍵方法:

思前想后,還是決定先貼下公司項(xiàng)目中用到的圖片上傳的核心方法,這里用到一個(gè)第三方的庫(kù): android-async-http.jar,自己到github下下這個(gè)庫(kù)~然后調(diào)用一下下面的方法即可,自己改下url!

上傳圖片的核心方法如下:

private void sendImage(Bitmap bm)
{
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 60, stream);
    byte[] bytes = stream.toByteArray();
    String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.add("img", img);
    client.post("http:xxx/postIcon", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int i, Header[] headers, byte[] bytes) {
            Toast.makeText(MainActivity.this, "Upload Success!", Toast.LENGTH_LONG).show();

        }
        @Override
        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            Toast.makeText(MainActivity.this, "Upload Fail!", Toast.LENGTH_LONG).show();
        }
    });
}

2.使用HttpConnection上傳文件:

簡(jiǎn)直臥槽...各種設(shè)置,各種麻煩...還是建議用1的方法吧,當(dāng)然,實(shí)在太閑可以看看, 有輪子可用還是先別自己造輪子了...

public class SocketHttpRequester   
{  
    /** 
     * 發(fā)送xml數(shù)據(jù) 
     * @param path 請(qǐng)求地址 
     * @param xml xml數(shù)據(jù) 
     * @param encoding 編碼 
     * @return 
     * @throws Exception 
     */  
    public static byte[] postXml(String path, String xml, String encoding) throws Exception{  
        byte[] data = xml.getBytes(encoding);  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setDoOutput(true);  
        conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);  
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
        conn.setConnectTimeout(5 * 1000);  
        OutputStream outStream = conn.getOutputStream();  
        outStream.write(data);  
        outStream.flush();  
        outStream.close();  
        if(conn.getResponseCode()==200){  
            return readStream(conn.getInputStream());  
        }  
        return null;  
    }  
      
    /** 
     * 直接通過(guò)HTTP協(xié)議提交數(shù)據(jù)到服務(wù)器,實(shí)現(xiàn)如下面表單提交功能: 
     *   <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data"> 
            <INPUT TYPE="text" NAME="name"> 
            <INPUT TYPE="text" NAME="id"> 
            <input type="file" name="imagefile"/> 
            <input type="file" name="zip"/> 
         </FORM> 
     * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試, 
     *                  因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試) 
     * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值 
     * @param file 上傳文件 
     */  
    public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception  
    {     
        //數(shù)據(jù)分隔線  
        final String BOUNDARY = "---------------------------7da2137580612";   
        //數(shù)據(jù)結(jié)束標(biāo)志"---------------------------7da2137580612--"  
        final String endline = "--" + BOUNDARY + "--/r/n";  
          
        //下面兩個(gè)for循環(huán)都是為了得到數(shù)據(jù)長(zhǎng)度參數(shù),依據(jù)表單的類型而定  
        //首先得到文件類型數(shù)據(jù)的總長(zhǎng)度(包括文件分割線)  
        int fileDataLength = 0;  
        for(FormFile uploadFile : files)  
        {  
            StringBuilder fileExplain = new StringBuilder();  
            fileExplain.append("--");  
            fileExplain.append(BOUNDARY);  
            fileExplain.append("/r/n");  
            fileExplain.append("Content-Disposition: form-data;name=/""+ uploadFile.getParameterName()+"/";filename=/""+ uploadFile.getFilname() + "/"/r/n");  
            fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"/r/n/r/n");  
            fileExplain.append("/r/n");  
            fileDataLength += fileExplain.length();  
            if(uploadFile.getInStream()!=null){  
                fileDataLength += uploadFile.getFile().length();  
            }else{  
                fileDataLength += uploadFile.getData().length;  
            }  
        }  
        //再構(gòu)造文本類型參數(shù)的實(shí)體數(shù)據(jù)  
        StringBuilder textEntity = new StringBuilder();          
        for (Map.Entry<String, String> entry : params.entrySet())   
        {    
            textEntity.append("--");  
            textEntity.append(BOUNDARY);  
            textEntity.append("/r/n");  
            textEntity.append("Content-Disposition: form-data; name=/""+ entry.getKey() + "/"/r/n/r/n");  
            textEntity.append(entry.getValue());  
            textEntity.append("/r/n");  
        }  
          
        //計(jì)算傳輸給服務(wù)器的實(shí)體數(shù)據(jù)總長(zhǎng)度(文本總長(zhǎng)度+數(shù)據(jù)總長(zhǎng)度+分隔符)  
        int dataLength = textEntity.toString().getBytes().length + fileDataLength +  endline.getBytes().length;  
          
        URL url = new URL(path);  
        //默認(rèn)端口號(hào)其實(shí)可以不寫  
        int port = url.getPort()==-1 ? 80 : url.getPort();  
        //建立一個(gè)Socket鏈接  
        Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);  
        //獲得一個(gè)輸出流(從Android流到web)  
        OutputStream outStream = socket.getOutputStream();  
        //下面完成HTTP請(qǐng)求頭的發(fā)送  
        String requestmethod = "POST "+ url.getPath()+" HTTP/1.1/r/n";  
        outStream.write(requestmethod.getBytes());  
        //構(gòu)建accept  
        String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*/r/n";  
        outStream.write(accept.getBytes());  
        //構(gòu)建language  
        String language = "Accept-Language: zh-CN/r/n";  
        outStream.write(language.getBytes());  
        //構(gòu)建contenttype  
        String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "/r/n";  
        outStream.write(contenttype.getBytes());  
        //構(gòu)建contentlength  
        String contentlength = "Content-Length: "+ dataLength + "/r/n";  
        outStream.write(contentlength.getBytes());  
        //構(gòu)建alive  
        String alive = "Connection: Keep-Alive/r/n";          
        outStream.write(alive.getBytes());  
        //構(gòu)建host  
        String host = "Host: "+ url.getHost() +":"+ port +"/r/n";  
        outStream.write(host.getBytes());  
        //寫完HTTP請(qǐng)求頭后根據(jù)HTTP協(xié)議再寫一個(gè)回車換行  
        outStream.write("/r/n".getBytes());  
        //把所有文本類型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)  
        outStream.write(textEntity.toString().getBytes());           
          
        //把所有文件類型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)  
        for(FormFile uploadFile : files)  
        {  
            StringBuilder fileEntity = new StringBuilder();  
            fileEntity.append("--");  
            fileEntity.append(BOUNDARY);  
            fileEntity.append("/r/n");  
            fileEntity.append("Content-Disposition: form-data;name=/""+ uploadFile.getParameterName()+"/";filename=/""+ uploadFile.getFilname() + "/"/r/n");  
            fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"/r/n/r/n");  
            outStream.write(fileEntity.toString().getBytes());  
            //邊讀邊寫  
            if(uploadFile.getInStream()!=null)  
            {  
                byte[] buffer = new byte[1024];  
                int len = 0;  
                while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1)  
                {  
                    outStream.write(buffer, 0, len);  
                }  
                uploadFile.getInStream().close();  
            }  
            else  
            {  
                outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);  
            }  
            outStream.write("/r/n".getBytes());  
        }  
        //下面發(fā)送數(shù)據(jù)結(jié)束標(biāo)志,表示數(shù)據(jù)已經(jīng)結(jié)束  
        outStream.write(endline.getBytes());          
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
        //讀取web服務(wù)器返回的數(shù)據(jù),判斷請(qǐng)求碼是否為200,如果不是200,代表請(qǐng)求失敗  
        if(reader.readLine().indexOf("200")==-1)  
        {  
            return false;  
        }  
        outStream.flush();  
        outStream.close();  
        reader.close();  
        socket.close();  
        return true;  
    }  
      
    /**  
     * 提交數(shù)據(jù)到服務(wù)器  
     * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試)  
     * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值  
     * @param file 上傳文件  
     */  
    public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception  
    {  
       return post(path, params, new FormFile[]{file});  
    }  
    /** 
     * 提交數(shù)據(jù)到服務(wù)器 
     * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用http://www.baidu.com或http://192.168.1.10:8080這樣的路徑測(cè)試) 
     * @param params 請(qǐng)求參數(shù) key為參數(shù)名,value為參數(shù)值 
     * @param encode 編碼 
     */  
    public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception  
    {  
        //用于存放請(qǐng)求參數(shù)  
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
        for(Map.Entry<String, String> entry : params.entrySet())  
        {  
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
        }  
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);  
        HttpPost httppost = new HttpPost(path);  
        httppost.setEntity(entity);  
        //看作是瀏覽器  
        HttpClient httpclient = new DefaultHttpClient();  
        //發(fā)送post請(qǐng)求    
        HttpResponse response = httpclient.execute(httppost);     
        return readStream(response.getEntity().getContent());  
    }  
    /** 
     * 發(fā)送請(qǐng)求 
     * @param path 請(qǐng)求路徑 
     * @param params 請(qǐng)求參數(shù) key為參數(shù)名稱 value為參數(shù)值 
     * @param encode 請(qǐng)求參數(shù)的編碼 
     */  
    public static byte[] post(String path, Map<String, String> params, String encode) throws Exception  
    {  
        //String params = "method=save&name="+ URLEncoder.encode("老畢", "UTF-8")+ "&age=28&";//需要發(fā)送的參數(shù)  
        StringBuilder parambuilder = new StringBuilder("");  
        if(params!=null && !params.isEmpty())  
        {  
            for(Map.Entry<String, String> entry : params.entrySet())  
            {  
                parambuilder.append(entry.getKey()).append("=")  
                    .append(URLEncoder.encode(entry.getValue(), encode)).append("&");  
            }  
            parambuilder.deleteCharAt(parambuilder.length()-1);  
        }  
        byte[] data = parambuilder.toString().getBytes();  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        //設(shè)置允許對(duì)外發(fā)送請(qǐng)求參數(shù)  
        conn.setDoOutput(true);  
        //設(shè)置不進(jìn)行緩存  
        conn.setUseCaches(false);  
        conn.setConnectTimeout(5 * 1000);  
        conn.setRequestMethod("POST");  
        //下面設(shè)置http請(qǐng)求頭  
        conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");  
        conn.setRequestProperty("Accept-Language", "zh-CN");  
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");  
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
        conn.setRequestProperty("Connection", "Keep-Alive");  
          
        //發(fā)送參數(shù)  
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
        outStream.write(data);//把參數(shù)發(fā)送出去  
        outStream.flush();  
        outStream.close();  
        if(conn.getResponseCode()==200)  
        {  
            return readStream(conn.getInputStream());  
        }  
        return null;  
    }  
      
    /**  
     * 讀取流  
     * @param inStream  
     * @return 字節(jié)數(shù)組  
     * @throws Exception  
     */  
    public static byte[] readStream(InputStream inStream) throws Exception  
    {  
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = -1;  
        while( (len=inStream.read(buffer)) != -1)  
        {  
            outSteam.write(buffer, 0, len);  
        }  
        outSteam.close();  
        inStream.close();  
        return outSteam.toByteArray();  
    }  
}  


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)