Android异步上传图片到PHP服务器

时间:2022-01-07 17:23:42

原理

android客户端模拟一个http的post请求到服务器端,服务器端接收相应的post请求后,返回响应信息给给客户端。

背景

网上很多上传到java服务器上的,找了好久,找到了上传到php的了,思路跟我当初想的差不多,就是post过去。废话不多说,直接上图看代码。

Android异步上传图片到PHP服务器

Android异步上传图片到PHP服务器

Android异步上传图片到PHP服务器

php代码

?
1
2
3
4
5
6
7
8
9
<?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'];
}
?>

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
private void uploadfile(string uploadurl)
{
string end = " ";
string twohyphens = "--";
string boundary = "******";
try
{
url url = new url(uploadurl);
httpurlconnection httpurlconnection = (httpurlconnection) url
.openconnection();//http连接
// 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 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);//post传递过去的编码
dataoutputstream dos = new dataoutputstream(
httpurlconnection.getoutputstream());//输出流
dos.writebytes(twohyphens + boundary + end);
dos.writebytes("content-disposition: form-data; name="uploadedfile"; 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(twohyphens + boundary + twohyphens + end);
dos.flush();
inputstream is = httpurlconnection.getinputstream();//http输入,即得到返回的结果
inputstreamreader isr = new inputstreamreader(is, "utf-8");
bufferedreader br = new bufferedreader(isr);
string result = br.readline();
toast.maketext(this, result, toast.length_long).show();//将结果输出
dos.close();
is.close();
} catch (exception e)
{
e.printstacktrace();
settitle(e.getmessage());
}
}

因为安卓4.0之后耗时间的操作要求都在非ui线程中操作,即将前面的asynctask拿来用了吧~

asynctask传送门:http://www.zzvips.com/article/159411.html

在这个类中,将上传的操作放在doinbackground当中,可以有progressdialog显示上传了多少:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// read file
bytesread = fileinputstream.read(buffer, 0, buffersize);
while (bytesread > 0) {
outputstream.write(buffer, 0, buffersize);
length += buffersize;
progress = (int) ((length * 100) / totalsize);
publishprogress(progress);
bytesavailable = fileinputstream.available();
buffersize = math.min(bytesavailable, maxbuffersize);
bytesread = fileinputstream.read(buffer, 0, buffersize);
}
outputstream.writebytes(lineend);
outputstream.writebytes(twohyphens + boundary + twohyphens
+ lineend);
publishprogress(100);

还有就是,注意权限哟:

?
1
<uses-permission android:name="android.permission.internet" />

以上内容给大家介绍了android异步上传图片到php服务器,希望本文分享能够给大家带来帮助。