Table of Contents
一、通过网页上传图片到PHP服务器
二、android原生POST上传文件
Home php教程 php手册 android原生POST、httpClient4.X实现向PHP服务器上传文件

android原生POST、httpClient4.X实现向PHP服务器上传文件

Jun 06, 2016 pm 07:55 PM
android post Native

前言:虽然网上代码一堆,相对减轻了尝试的复杂程度,但真正运行起来还是有各种问题的,没有源码直接运行是一个很大问题,我尝试了一天之后,终于弄懂了些门路,分享给大家,对于原生POST方式上传,因为我也不会用这种方式上传文件,效率低,不好用,所以我

前言:虽然网上代码一堆,相对减轻了尝试的复杂程度,但真正运行起来还是有各种问题的,没有源码直接运行是一个很大问题,我尝试了一天之后,终于弄懂了些门路,分享给大家,对于原生POST方式上传,因为我也不会用这种方式上传文件,效率低,不好用,所以我也没有深究具体代码及原理,但我给出的代码是可行的,我们先从PHP在浏览器中上传图片到服务器开始,然后逐步讲解通过android是如何上传的,android的那些参数该如何构造。

一、通过网页上传图片到PHP服务器

具体讲解参考我这篇文章《不刷新实现图片上传功能》,里面源码啥啥的都有,下面我只贴出前后台部分代码,讲解一个问题

前台部分代码:

1

2

3

4

5

6

7

8

9

10

11

<div id="upLoad">

    <div id="processing" style="font-size:10px;"></div>

    <form action="post2.php" method="post" enctype="multipart/form-data" target="form-target" onsubmit="startUpload();">

        <tr>

            <td><span>上传到图库</span></td>

            <td><input type="file" name="upfile" id="file" style="margin-left:10px"></td>

            <td><input type="submit" value="上传" style="margin-left:25px;padding-left:5px;padding-right:5px;"></td>

        </tr>

    </form>

<iframe style="width:0; height:0; border:0;" name="form-target"></iframe>

</div>

Copy after login

注意一个input控件type='file',name='upfile'

后台部分代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

$filePath="temp/";

if (!file_exists($filePath)){//如果指定文件夹不存在,则创建文件夹

            mkdir($filePath , 0777);

     }

//重新定义文件路径及文件名

//分离文件路径,分离结果为:pathinfo() 返回一个关联数组包含有 path 的信息。包括以下的数组单元:dirname,basename 和 extension。

$houzhui = pathinfo($_FILES['upfile']['name']);

//判断格式是否是图片格式

if ( !in_array($houzhui['extension'],array('jpg','gif','png','JPG','GIF','PNG')) ) {

    $result=2;

}else{

    $name=$filePath."newName".'.'.$houzhui['extension'];

    //移动上传的临时文件,为新的文件

    //如果移动成功,输出相应内容

    if(move_uploaded_file($_FILES['upfile']['tmp_name'],$name))

    {

        $result=0;

    }

    //如果移动失败

    else{

        $result=-1;

    }

}

Copy after login

这里注意一个变量:$_FILES['upfile']['name'],$_FILES的第一个参数是upfile,表示就是接收我们上面定义的 ,所传上来的文件

二、android原生POST上传文件

基本用不到,不细讲了,直接看源码吧(源码在最后)

三、httpClient 4.X实现向PHP服务器上传文件

上效果图:

android原生POST、httpClient4.X实现向PHP服务器上传文件

android端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

private void uploadFile(String uploadUrl) throws Exception

{

        HttpClient httpclient = new DefaultHttpClient();

        httpclient.getParams().setParameter(

                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(uploadUrl);

         

        MultipartEntity entity = new MultipartEntity();

         

        File file = new File(srcPath);

        FileBody fileBody = new FileBody(file);

        entity.addPart("uploadedfile", fileBody);

             

        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);

         

        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {           

            Toast.makeText(this, EntityUtils.toString(resEntity), Toast.LENGTH_LONG).show();

        }

 

        httpclient.getConnectionManager().shutdown();

 

}

Copy after login
这里注意一下这小段代码:

1

2

3

4

5

MultipartEntity entity = new MultipartEntity();    

File file = new File(srcPath);

FileBody fileBody = new FileBody(file);

entity.addPart("uploadedfile", fileBody);      

httppost.setEntity(entity);

Copy after login

2、下句:entity.addPart("uploadedfile", fileBody);这句,把我们的fileBody加入到表单中,而前面的uploadedfile就相当于input type=file name='xxx'的name字段的值,这就是为什么在PHP接收中,$_FILES['uploadedfile']['name'],这个$_FILES第一个参数要与entity.addPart("uploadedfile", fileBody);的第一个参数一样的原因;

看服务器端(PHP):

1

2

3

4

5

6

7

<?php $target_path  = "./upload/";//接收文件目录

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

   echo "The file "basename( $_FILES['uploadedfile']['name']). " has been uploaded";

else{

   echo "There was an error uploading the file, please try again!" . $_FILES['uploadedfile']['error'];

}

Copy after login

难度不大,只注意一点:$_FILES['uploadedfile']['tmp_name']的第一个参数要与android代码中的entity.addPart("uploadedfile", fileBody);第一个参数名保持一致;
在源码中,这对这种方法稍微进行了扩充,同时上传两个图片到PHP服务器;


上源码啦:http://download.csdn.net/detail/harvic880925/6769671(不要分,仅供分享)

实例运行方法:

1、使用真机测试,使服务器与真机处于同一局域网中;
2、将Desert.jpg和1.jpg复制到手机sdcard根目录下,即Desert.jpg所处的位置为:sdcard/Desert.jpg和sdcard/1.jpg;
3、将receive_file.php,放在Apache服务器htdocs目录下;
4、将android代码中的:222.195.151.19,改成自己电脑PHP服务器的地址;


http://blog.csdn.net/harvic880925/article/details/17565481

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles