Android上传图片的方式
Android上传图片并附带数据使用文件流
关于Android图片上传的两种方式,一种是文件流的方式上传,图片转换成二进制上传;另一种是把图片转成Base64方式上传.
1.文件流上传图片、(图片上传需要一个图片的路径,同时调用本地相册或者拍照可以返回的图片路径,假设获得的图片路径是PicPath)
首先封装要发送的数据,数据封装好了以后用 String path= = URLEncodedUtils.format(Parameters,"UTF-8");来编码;然后开启线程发送数据.
activity:
封装数据
@SuppressLint("SimpleDateFormat")
public String getrubbishIfo() throws IOException {
final List<NameValuePair> Parameters = new ArrayList<NameValuePair>();
Parameters.add(new BasicNameValuePair("runame", thingname.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("ruleibie", fenlei
.getSelectedItem().toString()));
Parameters.add(new BasicNameValuePair("rubeizhu", beizhu.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("rufreetime", freetime
.getSelectedItem().toString()));
Parameters.add(new BasicNameValuePair("userphone", userphone));
Parameters.add(new BasicNameValuePair("address", address.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("username", username));
Parameters.add(new BasicNameValuePair("rudate", ""));
System.out.println("Parameters:" + Parameters);
String path=URLEncodedUtils.format(Parameters,"UTF-8");
System.out.println(path+"0000000000000000000");
return path;
}
Handler myhandler = new Handler() {
public void handleMessage(Message msg) {
String text = (String) msg.obj;
if (text.equals("yes")) {
Log.d("click", "不为空了");
Toast.makeText(getApplicationContext(), "发布成功!!!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "发布失败!!!",
Toast.LENGTH_LONG).show();
}
};
};
//提交数据
class tijiaoListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
UploadFile_image up=new UploadFile_image();
try {
String
path = getrubbishIfo();
String restr=up.uploadFile(HttpPath.FABU_PATH+"?"+path, picpath);//HttpPath.FABU_PATH为路径,将封装好的数据path绑到路径后传递给服务器,picpath为图片路径
Message message = myhandler.obtainMessage();
message.obj = restr;
myhandler.sendMessage(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
下边是工具类UploadFile_image up也就是图片格式准换的方式;
package com.back.util;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile_image {
private String newName ="image.jpg";
/* 上传文件至Server的方法 */
public String uploadFile(String actionUrl,String picPath)
{
String end ="\r\n";
String twoHyphens ="--";
String boundary ="*****";//边界标识
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);//允许输入流
con.setDoOutput(true);//允许输出流
con.setUseCaches(false);//不允许使用缓存
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty 设置编码 */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",// "multipart/form-data"这个参数来说明我们这传的是文件不是字符串了
"multipart/form-data;boundary="+boundary);
/* 设置DataOutputStream */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+
"name=\"file1\";filename=\""+
newName +"\""+ end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream =new FileInputStream(picPath);
/* 设置每次写入1024bytes */
int bufferSize =1024;
byte[] buffer =new byte[bufferSize];
int length =-1;
/* 从文件读取数据至缓冲区 */
while((length = fStream.read(buffer)) !=-1)
{
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) !=-1 )
{
b.append( (char)ch );
}
/* 将Response显示于Dialog */
// showDialog("上传成功"+b.toString().trim());
/* 关闭DataOutputStream */
ds.close();
//返回客户端返回的信息
return b.toString().trim();
}
catch(Exception e)
{
//showDialog("上传失败"+e);
return null;
}
}
}
安卓端结束;
下边是服务器端代码
package cn.back.servlet.app;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import cn.back.domin.Things;
import cn.back.service.backservice;
import cn.back.service.backserviceImp;
public class UploadImageapp extends HttpServlet {
private String name;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接受图片
String temp = request.getSession().getServletContext().getRealPath("/")
+ "temp"; // 临时目录
System.out.println("temp=" + temp);
String loadpath = request.getSession().getServletContext()
.getRealPath("/")
+ "imagething"; // 上传文件存放目录
System.out.println("loadpath=" + loadpath);
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(1 * 1024 * 1024); // 设置允许用户上传文件大小,单位:字节
fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节
fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
// 开始读取上传信息
int index = 0;
List fileItems = null;
try {
fileItems = fu.parseRequest(request);
System.out.println("fileItems=" + fileItems);
} catch (Exception e) {
e.printStackTrace();
}
Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
name = item.getName();// 获取上传文件名,包括路径
name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
int point = name.indexOf(".");
// name=(new
// Date()).getTime()+name.substring(point,name.length())+index;
name = (new Date()).getTime()
+ name.substring(point, name.length());
index++;
File fNew = new File(loadpath,name);
try {
item.write(fNew);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else// 取出不是文件域的所有表单信息
{
String
fieldvalue = item.getString();
// 如果包含中文应写为:(转为UTF-8编码)
// String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
}
//图片接受完毕
//接收数据并存储
String path="/back/imagething/"+name;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Date now = new Date();
DateFormat dataFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");// 2014/08/31// 04:08:26获取时间
String fabutime = dataFormat.format(now);
backservice bs = new backserviceImp();
Things t = new Things();
t.setThingname(new String(request.getParameter("runame").getBytes("ISO_8859-1"),"UTF-8"));
//由于是用URLEncodedUtils编码所以解码比较麻烦,关于解码我有一篇单独的博客写编码
System.out.println(name+"11111111111111111111111");
t.setThingleibie(new String(request.getParameter("ruleibie").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingbeizhu(new String(request.getParameter("rubeizhu").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingfreetime(new String(request.getParameter("rufreetime").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingimg(path);
t.setThingfabutime(fabutime);
t.setUsername(new String(request.getParameter("username").getBytes("ISO_8859-1"),"UTF-8"));
t.setUserphone(new String(request.getParameter("userphone").getBytes("ISO_8859-1"),"UTF-8"));
t.setAddress(new String(request.getParameter("address").getBytes("ISO_8859-1"),"UTF-8"));
int flag = bs.addBack(t);
if (flag != 0) {
System.out.println("app注册成功");
}else
{
System.out.println("0000000000000");
}
//发送数据
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();//发送数据
out.write("yes");
out.flush();
out.close();
}
}
Android上传图片的方式相关推荐
- android上传本地图片到服务器上,Android使用post方式上传图片到服务器的方法
本文实例讲述了Android使用post方式上传图片到服务器的方法.分享给大家供大家参考,具体如下: /** * 上传文件到服务器类 * * @author tom */ public class U ...
- android用上传图片到服务器上,Android使用post方式上传图片到服务器的方法
本文实例讲述了Android使用post方式上传图片到服务器的方法.分享给大家供大家参考,具体如下: /** * 上传文件到服务器类 * * @author tom */ public class U ...
- android cpu调度策略_「性能优化3.0」Android线程调度异步方式汇总
线程调度与线程调度模型 任意时刻,只有一个线程占用 CPU,处于运行状态.而多线程并发执行就是轮流获取 CPU 执行权. 分时调用模型 轮流获取 CPU 执行权,均分 CPU 执行时间. 抢占式调度模 ...
- Android中BindService方式使用的理解
Android中BindService方式使用的理解 - 唯一小神 - 博客园 最近学习了一下Android里面的Service的应用,在BindService部分小卡了一下,主要是开始没有彻底理解为 ...
- android源代码下载AE 文字样式,阅读Android framework源代码方式
阅读Android framework源代码方式 点击标题下「蓝色微信名」可快速关注 阅读源代码的方式有很多,这里只讲其中的两种方式. 一.AndroidXRef(强烈推荐) 这种方式速度快,操作简单 ...
- android intent拍照,Android通过Intent方式调用相机拍照取得图片
Android通过Intent方式调用相机拍照取得图片 AndroidManifest.XML 权限设置: XML布局设置: 代码: public classMainActivityextendsAp ...
- php android 图片上传,android上传图片到PHP的过程详解
这篇文章主要介绍了android上传图片到PHP的过程详解,需要的朋友可以参考下 今天在做上传头像的时候,总是提交连接超时错误,报错信息如下:XXXXXXSokcetTimeOutXXXXXXXX 然 ...
- android圆形点击效果,Android 三种方式实现自定义圆形页面加载中效果的进度条
[实例简介] Android 三种方式实现自定义圆形页面加载中效果的进度条 [实例截图] [核心代码] ad376a86-a9aa-49bc-8cea-321bcff2c0c3 └── AnimRou ...
- Android 多线程实现方式
该原创文章首发于微信公众号"字节流动" Android 多线程实现方式 通常来说,一个应用至少有一个进程,而一个进程至少有一个线程. 线程是 CPU 调度的基本单位,进程是系统资源 ...
- Android中静态方式破解某App实现所有视频app去除广告功能
转: Android中静态方式破解某App实现所有视频app去除广告功能 作为一个屌丝程序猿也有追剧的时候,但是当打开视频app的时候,那些超长的广告已经让我这个屌丝无法忍受了,作为一个程序猿看视频 ...
最新文章
- Windows 服务器操作系统安全设置加固方法
- “刷脸”之后 声纹识别有望成为新秀
- Saltstack使用(基础)
- 腾讯扩招3000人,产品硬核技能被曝光,看完我跪了!
- 睡眠经济的尽头,会是智能床垫吗?
- GOPROXY环境变量中direct的含义与用途
- python性能测试模块_技巧python模块性能测试-阿里云开发者社区
- raster | 栅格对象如何用于非空间模型的预测?
- 10个最受欢迎的 JavaScript 框架,它们的主要特征和功能
- 一主多备几影响 oracle,1个主库配置多个备库的问题
- LongAdder源码分析
- 刷屏!马化腾:腾讯只是一家普通公司,随时可以被替换
- Apache Server搭建独立图片服务器
- matpower常用标准算例
- 基于FileOpen的PDF文档加密
- 使用grldr文件引导windows xp、ubuntu系统
- 怎么将计算机的触摸鼠标锁定,终极:如何在笔记本电脑上锁定触摸鼠标
- c程序怎样往mysql里面添加字符串指针指向的字符串
- Linux系统Docker配置阿里云镜像加速器
- 推荐一个Mac上的软件卸载工具