背景                                                                                          

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

php代码                                                                                    

<?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代码                                                                              

上传的主要代码:

private void uploadFile(String uploadUrl)
{
String end = "\r\n";
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.cnblogs.com/yydcdut/p/3707960.html

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

// 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);

还有就是,注意权限哟:

<uses-permission android:name="android.permission.INTERNET" />

我是天王盖地虎的分割线                                                                 

源代码:http://pan.baidu.com/s/1dD1Qx01

Update.zip

参考:http://blog.csdn.net/sxwyf248/article/details/7012496

转载请注明出处:http://www.cnblogs.com/yydcdut/p/3720635.html

Android -- 图片异步上传到PHP服务器的更多相关文章

  1. html5图片异步上传/ 表单提交相关

    1 form 表单 get/post提交时候. action地址(或者啥ajax的url地址) 会涉及到跨域问题 常见跨域问题http://www.cnblogs.com/rainman/archiv ...

  2. AsyncTask异步上传文本到服务器

    服务器代码:用于接收客户端信息 package ches; import java.io.IOException; import java.io.PrintWriter; import javax.s ...

  3. Ajax图片异步上传并回显

    1.jsp页面 <td width="20%" class="pn-flabel pn-flabel-h"></td> <td w ...

  4. 一个完整的springmvc + ajaxfileupload实现图片异步上传的案例

    一,原理 详细原理请看这篇文章 springmvc + ajaxfileupload解决ajax不能异步上传图片的问题.java.lang.ClassCastException: org.apache ...

  5. Android 通过httppost上传文本文件到服务器。

    /** * 往服务器上上传文本 比如log日志 * @param urlstr 请求的url * @param uploadFile log日志的路径 * /mnt/shell/emulated/0/ ...

  6. ajax+XMLHttpRequest里的FormData实现图片异步上传

    发这篇博客的时候我是自己在研究这个XMLHttpRequest请求,在别人的博客上面知道XMLHttpRequest新加了一个FormData的东西,好像现在APP请求后台也有用这种方式的吧. 别的不 ...

  7. base64字符串转文件,以及ngImgCrop裁剪图片并上传保存到服务器示例

    base64字符串是包含文件格式的文件字符串,例如:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElE ...

  8. asp.net使用jquery.form实现图片异步上传

    首先我们需要做准备工作: jquery下载:http://files.cnblogs.com/tianguook/jquery1.8.rar jquery.form.js下载:http://files ...

  9. Android图片压缩上传(二)

    之前有用到libjpeg,还是有一定的局限性,最近用了一个新的方式,效果还是挺不错,随着作者的版本更新,Bug也随之变少,目前项目中运用已上线. 1.之前的方式Android图片压缩,不失真,上线项目 ...

随机推荐

  1. JavaSE基础之矩阵运算

    JavaSE基础之矩阵运算 1.矩阵类:Matrix.java 包括矩阵的加.乘运算,行列式的求解,最大最小元素等 package cn.com.zfc.help; import java.text. ...

  2. bzoj1211: [HNOI2004]树的计数 prufer编码

    题目链接 bzoj1211: [HNOI2004]树的计数 题解 prufer序 可重排列计数 代码 #include<bits/stdc++.h> using namespace std ...

  3. BZOJ3996 TJOI2015线性代数

    先把矩阵式子化简 原式=∑i=1n∑j=1nA[i]∗B[i][j]∗A[j]−∑i=1nA[i]∗C[i] 因此我们发现问题转化为选取一个点所获收益是B[i][j],代价是C[i][j] 这是一个最 ...

  4. 方程式0day图形化利用工具

    最近方程式的漏洞着实活了一把,分析了下githup上面的文件目录,找到了利用文件,主要是针对windows主机的SMB.RDP协议进行攻击,因为我主要根据他们提供的payload的程序,利用这两个模块 ...

  5. UC浏览器 垂直水平居中

    今天使用下述方式定义水平垂直居中不起作用 #box{ position: fixed; left:; right:; top:; bottom:; margin: auto; } 然后改用: #box ...

  6. python开发_webbrowser_浏览器控制模块

    ''' python的webbrowser模块支持对浏览器进行一些操作 主要有以下三个方法: webbrowser.open(url, new=0, autoraise=True) webbrowse ...

  7. THE CUSTOMISER

    http://www.wanga.com/cu.php The Customiser incorporates all of the features of Magic Mouse. It also ...

  8. ASP.NET中Cookie跨域的问题及解决代码

    ASP.NET中Cookie跨域的问题及解决代码 http://www.liyumei.net.cn/post/share18.html Cookies揭秘  http://www.cnblogs.c ...

  9. hibernate一级缓存,二级缓存和查询缓存

    一级缓存 (必然存在)  session里共享缓存,伴随session的生命周期存在和消亡:   1. load查询实体支持一级缓存 2. get查询实体对象也支持 3. save保存的实体对象会缓存 ...

  10. 25LINQ拾遗及实例

      投影 □ 遍历数组索引,Select获取 int[] indexes = {0, 2}; string[] strs = {"a", "b", " ...