Maison > php教程 > php手册 > Android使用HttpClient实现文件上传到PHP服务器,并监控进度条

Android使用HttpClient实现文件上传到PHP服务器,并监控进度条

WBOY
Libérer: 2016-06-06 19:49:24
original
978 Les gens l'ont consulté

上传 服务器 端PHP 代码如下 : ? php $ target_path = ./tmp/ ;// 接收文件目录 $ target_path = $ target_path .( $ _FILES [ 'file' ][ 'name' ] ); $ target_path = iconv ( UTF-8 , gb2312 , $ target_path ); if ( move_uploaded_file ( $ _FILES [ 'f

Android使用HttpClient实现文件上传到PHP服务器,并监控进度条

上传

服务器端PHP

代码如下 :

<span></span><span>php</span>
    <span>$</span><span>target_path</span>  <span>=</span> <span>"./tmp/"</span><span>;//</span><span>接收文件目录</span>  
    <span>$</span><span>target_path</span> <span>=</span> <span>$</span><span>target_path</span><span>.(</span><span>$</span><span>_FILES</span><span>[</span><span>'file'</span><span>][</span><span>'name'</span><span>]</span><span>);</span>
    <span>$</span><span>target_path</span> <span>=</span> <span>iconv</span><span>(</span><span>"UTF-8"</span><span>,</span><span>"gb2312"</span><span>,</span> <span>$</span><span>target_path</span><span>);</span>
    <span>if</span><span>(</span><span>move_uploaded_file</span><span>(</span><span>$</span><span>_FILES</span><span>[</span><span>'file'</span><span>][</span><span>'tmp_name'</span><span>]</span><span>,</span> <span>$</span><span>target_path</span><span>))</span> <span>{</span>  
       <span>echo</span> <span>"The file "</span><span>.</span><span>(</span> <span>$</span><span>_FILES</span><span>[</span><span>'file'</span><span>][</span><span>'name'</span><span>]</span><span>)</span><span>.</span><span>" has been uploaded."</span><span>;</span>
    <span>}</span><span>else</span><span>{</span>  
       <span>echo</span> <span>"There was an error uploading the file, please try again! Error Code: "</span><span>.</span><span>$</span><span>_FILES</span><span>[</span><span>'file'</span><span>][</span><span>'error'</span><span>]</span><span>;</span>
    <span>}</span>
<span>?></span>
Copier après la connexion

监控进度实现

首先定义监听器接口,如下所示:

<span>//进度监听器接口</span>

<span>public</span> <span>interface</span> <span>ProgressListener</span> <span>{</span>
    <span>public</span> <span>void</span> <span>transferred</span><span>(</span><span>long</span> <span>transferedBytes</span><span>);</span>
<span>}</span>
Copier après la connexion

实现监控进度的关键部分就在于记录已传输字节数,所以我们需重载FilterOutputStream,重写其中的关键方法,实现进度监听的功能,如下所示,本例中首先重载的是HttpEntityWrapper,顾名思义,就是将需发送的HttpEntity打包,以便计算总字节数,代码如下:

<span> // ProgressOutHttpEntity:输出流(OutputStream)时记录已发送字节数</span>

<span>public</span> <span>class</span> <span>ProgressOutHttpEntity</span> <span>extends</span> <span>HttpEntityWr<span><span>app</span></span>er</span> <span>{</span>

    <span>private</span> <span>final</span> <span>ProgressListener</span> <span>listener</span><span>;</span>

    <span>public</span> <span>ProgressOutHttpEntity</span><span>(</span><span>final</span> <span>HttpEntity</span> <span>entity</span><span>,</span>
            <span>final</span> <span>ProgressListener</span> <span>listener</span><span>)</span> <span>{</span>
        <span>super</span><span>(</span><span>entity</span><span>);</span>
        <span>this</span><span>.</span><span>listener</span> <span>=</span> <span>listener</span><span>;</span>
    <span>}</span>

    <span>public</span> <span>static</span> <span>class</span> <span>CountingOutputStream</span> <span>extends</span> <span>FilterOutputStream</span> <span>{</span>

        <span>private</span> <span>final</span> <span>ProgressListener</span> <span>listener</span><span>;</span>
        <span>private</span> <span><span><span>long</span></span></span> <span>transferred</span><span>;</span>

        <span>CountingOutputStream</span><span>(</span><span>final</span> <span>OutputStream</span> <span>out</span><span>,</span>
                <span>final</span> <span>ProgressListener</span> <span>listener</span><span>)</span> <span>{</span>
            <span>super</span><span>(</span><span>out</span><span>);</span>
            <span>this</span><span>.</span><span>listener</span> <span>=</span> <span>listener</span><span>;</span>
            <span>this</span><span>.</span><span>transferred</span> <span>=</span> <span>0</span><span>;</span>
        <span>}</span>

        <span>@</span><span>Override</span>
        <span>public</span> <span>void</span> <span>write</span><span>(</span><span>final</span> <span>byte</span><span>[]</span> <span>b</span><span>,</span> <span>final</span> <span>int</span> <span>off</span><span>,</span> <span>final</span> <span>int</span> <span>len</span><span>)</span>
                <span>throws</span> <span>IOException</span> <span>{</span>
            <span>// NO, double-counting, as super.write(byte[], int, int)</span>
            <span>// delegates to write(int).</span>
            <span>// super.write(b, off, len);</span>
            <span>out</span><span>.</span><span>write</span><span>(</span><span>b</span><span>,</span> <span>off</span><span>,</span> <span>len</span><span>);</span>
            <span>this</span><span>.</span><span>transferred</span> <span>+=</span> <span>len</span><span>;</span>
            <span>this</span><span>.</span><span>listener</span><span>.</span><span>transferred</span><span>(</span><span>this</span><span>.</span><span>transferred</span><span>);</span>
        <span>}</span>

        <span>@</span><span>Override</span>
        <span>public</span> <span>void</span> <span>write</span><span>(</span><span>final</span> <span>int</span> <span>b</span><span>)</span> <span>throws</span> <span>IOException</span> <span>{</span>
            <span>out</span><span>.</span><span>write</span><span>(</span><span>b</span><span>);</span>
            <span>this</span><span>.</span><span>transferred</span><span>++</span><span>;</span>
            <span>this</span><span>.</span><span>listener</span><span>.</span><span>transferred</span><span>(</span><span>this</span><span>.</span><span>transferred</span><span>);</span>
        <span>}</span>

    <span>}</span>

    <span>@</span><span>Override</span>
    <span>public</span> <span>void</span> <span>writeTo</span><span>(</span><span>final</span> <span>OutputStream</span> <span>out</span><span>)</span> <span>throws</span> <span>IOException</span> <span>{</span>
        <span>this</span><span>.</span><span>wr<span><span>app</span></span>edEntity</span><span>.</span><span>writeTo</span><span>(</span><span>out</span> <span>instanceof</span> <span>CountingOutputStream</span> <span>?</span> <span>out</span>
                <span>:</span> <span>new</span> <span>CountingOutputStream</span><span>(</span><span>out</span><span>,</span> <span>this</span><span>.</span><span>listener</span><span>));</span>
    <span>}</span>
<span>}</span>
Copier après la connexion

最后就是使用上述实现的类和Httpclient进行上传并显示进度的功能,非常简单,代码如下,使用AsyncTask异步上传。

<span>public</span> <span>class</span> <span>FileUploadAsyncTask</span> <span>extends</span> <span>AsyncTask</span><span><span>File</span><span>,</span> <span>Integer</span><span>,</span> <span>String</span><span>></span> <span>{</span>

    <span>private</span> <span>String</span> <span>url</span> <span>=</span> <span>"http://192.168.83.213/receive_file.php"</span><span>;</span>
    <span>private</span> <span>Context</span> <span>context</span><span>;</span>
    <span>private</span> <span>ProgressDialog</span> <span>pd</span><span>;</span>
    <span>private</span> <span><span><span>long</span></span></span> <span>totalSize</span><span>;</span>

    <span>public</span> <span>FileUploadAsyncTask</span><span>(</span><span>Context</span> <span>context</span><span>)</span> <span>{</span>
        <span>this</span><span>.</span><span>context</span> <span>=</span> <span>context</span><span>;</span>
    <span>}</span>

    <span>@</span><span>Override</span>
    <span>protected</span> <span>void</span> <span>onPreExecute</span><span>()</span> <span>{</span>
        <span>pd</span> <span>=</span> <span>new</span> <span>ProgressDialog</span><span>(</span><span>context</span><span>);</span>
        <span>pd</span><span>.</span><span>setProgressStyle</span><span>(</span><span>ProgressDialog</span><span>.</span><span>STYLE_HORIZONTAL</span><span>);</span>
        <span>pd</span><span>.</span><span>setMessage</span><span>(</span><span>"上传中...."</span><span>);</span>
        <span>pd</span><span>.</span><span>setCancelable</span><span>(</span><span>false</span><span>);</span>
        <span>pd</span><span>.</span><span>show</span><span>();</span>
    <span>}</span>

    <span>@</span><span>Override</span>
    <span>protected</span> <span>String</span> <span>doInBackground</span><span>(</span><span>File</span><span>...</span> <span>params</span><span>)</span> <span>{</span>
        <span>// 保存需上传文件信息</span>
        <span>MultipartEntityBuilder</span> <span>entitys</span> <span>=</span> <span>MultipartEntityBuilder</span><span>.</span><span>create</span><span>();</span>
        <span>entitys</span><span>.</span><span>setMode</span><span>(</span><span>HttpMultipartMode</span><span>.</span><span>BROWSER_COMPATIBLE</span><span>);</span>
        <span>entitys</span><span>.</span><span>setCharset</span><span>(</span><span>Charset</span><span>.</span><span>forName</span><span>(</span><span>HTTP</span><span>.</span><span>UTF_8</span><span>));</span>

        <span>File</span> <span>file</span> <span>=</span> <span>params</span><span>[</span><span>0</span><span>];</span>
        <span>entitys</span><span>.</span><span>addPart</span><span>(</span><span>"file"</span><span>,</span> <span>new</span> <span>FileBody</span><span>(</span><span>file</span><span>));</span>
        <span>HttpEntity</span> <span>httpEntity</span> <span>=</span> <span>entitys</span><span>.</span><span>build</span><span>();</span>
        <span>totalSize</span> <span>=</span> <span>httpEntity</span><span>.</span><span>getContentLength</span><span>();</span>
        <span>ProgressOutHttpEntity</span> <span>progressHttpEntity</span> <span>=</span> <span>new</span> <span>ProgressOutHttpEntity</span><span>(</span>
                <span>httpEntity</span><span>,</span> <span>new</span> <span>ProgressListener</span><span>()</span> <span>{</span>
                    <span>@</span><span>Override</span>
                    <span>public</span> <span>void</span> <span>transferred</span><span>(</span><span><span><span>long</span></span></span> <span>transferedBytes</span><span>)</span> <span>{</span>
                        <span>publishProgress</span><span>((</span><span>int</span><span>)</span> <span>(</span><span>100</span> <span>*</span> <span>transferedBytes</span> <span>/</span> <span>totalSize</span><span>));</span>
                    <span>}</span>
                <span>});</span>
        <span>return</span> <span>uploadFile</span><span>(</span><span>url</span><span>,</span> <span>progressHttpEntity</span><span>);</span>
    <span>}</span>

    <span>@</span><span>Override</span>
    <span>protected</span> <span>void</span> <span>onProgressUpdate</span><span>(</span><span>Integer</span><span>...</span> <span>progress</span><span>)</span> <span>{</span>
        <span>pd</span><span>.</span><span>setProgress</span><span>((</span><span>int</span><span>)</span> <span>(</span><span>progress</span><span>[</span><span>0</span><span>]));</span>
    <span>}</span>

    <span>@</span><span>Override</span>
    <span>protected</span> <span>void</span> <span>onPostExecute</span><span>(</span><span>String</span> <span>result</span><span>)</span> <span>{</span>
        <span>pd</span><span>.</span><span>dismiss</span><span>();</span>
        <span>Toast</span><span>.</span><span>makeText</span><span>(</span><span>context</span><span>,</span> <span>result</span><span>,</span> <span>Toast</span><span>.</span><span>LENGTH_SHORT</span><span>).</span><span>show</span><span>();</span>
    <span>}</span>

    
<span>     //上传文件到<span>服务器</span></span>
<span>  //<span>服务器</span>地址</span>
<span>     //文件</span>

    <span>public</span> <span>static</span> <span>String</span> <span>uploadFile</span><span>(</span><span>String</span> <span>url</span><span>,</span> <span>ProgressOutHttpEntity</span> <span>entity</span><span>)</span> <span>{</span>
        <span>HttpClient</span> <span>httpClient</span> <span>=</span> <span>new</span> <span>DefaultHttpClient</span><span>();</span>
        <span>httpClient</span><span>.</span><span>getParams</span><span>().</span><span>setParameter</span><span>(</span>
                <span>CoreProtocolPNames</span><span>.</span><span>PROTOCOL_VERSION</span><span>,</span> <span>HttpVersion</span><span>.</span><span>HTTP_1_1</span><span>);</span>
        <span>// 设置连接超时时间</span>
        <span>httpClient</span><span>.</span><span>getParams</span><span>().</span><span>setParameter</span><span>(</span>
                <span>CoreConnectionPNames</span><span>.</span><span>CONNECTION_TIMEOUT</span><span>,</span> <span>5000</span><span>);</span>
        <span>HttpPost</span> <span>httpPost</span> <span>=</span> <span>new</span> <span>HttpPost</span><span>(</span><span>url</span><span>);</span>
        <span>httpPost</span><span>.</span><span>setEntity</span><span>(</span><span>entity</span><span>);</span>
        <span>try</span> <span>{</span>
            <span>HttpResponse</span> <span>httpResponse</span> <span>=</span> <span>httpClient</span><span>.</span><span>execute</span><span>(</span><span>httpPost</span><span>);</span>
            <span>if</span> <span>(</span><span>httpResponse</span><span>.</span><span>getStatusLine</span><span>().</span><span>getStatusCode</span><span>()</span> <span>==</span> <span>HttpStatus</span><span>.</span><span>SC_OK</span><span>)</span> <span>{</span>
                <span>return</span> <span>"文件上传成功"</span><span>;</span>
            <span>}</span>
        <span>}</span> <span>catch</span> <span>(</span><span>ClientProtocolException</span> <span>e</span><span>)</span> <span>{</span>
            <span>e</span><span>.</span><span>printStackTrace</span><span>();</span>
        <span>}</span> <span>catch</span> <span>(</span><span>ConnectTimeoutException</span> <span>e</span><span>)</span> <span>{</span>
            <span>e</span><span>.</span><span>printStackTrace</span><span>();</span>
        <span>}</span> <span>catch</span> <span>(</span><span>Exception</span> <span>e</span><span>)</span> <span>{</span>
            <span>e</span><span>.</span><span>printStackTrace</span><span>();</span>
        <span>}</span> <span>finally</span> <span>{</span>
            <span>if</span> <span>(</span><span>httpClient</span> <span>!=</span> <span>null</span> <span>&&</span> <span>httpClient</span><span>.</span><span>getConnectionManager</span><span>()</span> <span>!=</span> <span>null</span><span>)</span> <span>{</span>
                <span>httpClient</span><span>.</span><span>getConnectionManager</span><span>().</span><span>shutdown</span><span>();</span>
            <span>}</span>
        <span>}</span>
        <span>return</span> <span>"文件上传失败"</span><span>;</span>
    <span>}</span>

<span>}</span></span>
Copier après la connexion

源码下载地址 :下载

安度博客 ? Android使用HttpClient实现文件上传到PHP服务器,并监控进度条

备份下载地址:http://download.csdn.net/detail/jdsjlzx/8486479

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal