android上传图片并附带上传数据,文件流
关于android的图片上传有两种方式,一种是以文件流的方式上传,图片转换成二进制上穿。另一种是把图片转成base64方式上传,这篇博客我只介绍文件流,关于base64方式会在下一篇博客中介绍!
首先是安卓端;图片上传我们需要一个图片的路径,同过调用本地相册或者拍照可以返回图片路径,这个在这里就不说了;假设我们获得图片路径为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();
}
}
服务器端结束;大功告成,关于base64上传,会在下一篇博客中写。
android上传图片并附带上传数据,文件流相关推荐
- mysql导入微信小程序云开发_微信小程序-云开发数据库上传json文件
小程序新增了云开发功能,对于个人开发者是个利好消息.可以省去购买服务器,购买域名以及繁琐配置等步骤,减轻了开发者的负担.至于如何云开发我就不在这里赘述了,请移步微信小程序云开发官方文档,说的很清楚.这 ...
- android volley 上传图片 和参数,Android使用Volley实现上传文件功能
一个项目中用到的使用Volley上传头像文件的例子,供大家参考,具体内容如下 /** * Created by wangshihui on 2015/11/30. * 上传文件 * url:..... ...
- Android实现拍照选择相册图片上传图片(多图片上传)功能
安卓多图片上传代码 直接上代码 1.主程序入口XML文件 <?xml version="1.0" encoding="utf-8"?> <ma ...
- 移动端上传大文件到服务器,android上传大文件到服务器地址
android上传大文件到服务器地址 内容精选 换一换 安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ.exe.在本地主机和Windows云服务器 ...
- 后台上传数据php代码,jQuery传递数据同时上传文件到php后台的问题
各位大神们好,我是一名学生正在自学编程,一段手机上传图片程序如下: 1.前端有一个上传框,上传图片后会自动生成预览图 2.如下程序是部分js文件,一些无关的代码已经删掉了, 3.后台post.php页 ...
- 后端——获取提交的数据(GET、 POST)、获取上传的文件、常见的网络请求
目录 一.获取提交的数据 1.接收GET请求的数据: 1.ajax-get 2.axios-get 3.浏览器的地址栏-get 4.a标签的href属性-get 5.img-src-get 6.lin ...
- Android之使用Http协议实现文件上传示例(上传MP3文件)
注意一般使用Http协议上传的文件都比较小,一般是小于2M 这里示例是上传一个小的MP3文件 1.主Activity:MainActivity.java view plain public class ...
- Android(安卓)上传文件到阿里云点播,阿里云点播转码
Android(安卓)上传文件到阿里云点播,阿里云点播转码 文章目录 Android(安卓)上传文件到阿里云点播,阿里云点播转码 一:登录阿里云点播平台配置添加转码模板组 1:需要什么参数,可自行填写 ...
- Android基础—基于Socket实现上传大文件
上节中我们给大家接触了Socket的一些基本概念以及使用方法,然后写了一个小猪简易聊天室的 Demo,相信大家对Socket有了初步的掌握,本节我们来学习下使用Socket来实现大文件的断点续传! 这 ...
最新文章
- 深圳杯---无线回传拓扑规划
- KOFLive Beta 下载情况及用户反馈
- 关节点(atriculation point)算法
- post请求与get请求的差别
- wpcap包含目录如何在2010中进行全局设置
- android 无法显示SD卡目录,Android studio无法在SD卡上创建新目录?
- Python示例-Logging
- 在线判题系统hustoj的搭建
- oracle linux6 u盘安装,Oracle Enterprise Linux/Redhat Linux 6.0 U盘安装方法
- LeedCode刷题
- VS2008下改变项目的默认属性
- Confuser.crproj
- nero10 序列号
- candence的图纸大小设置_标准制图图纸尺寸大小
- WebGL切换着色器 绘制不同物体
- 北京邮电大学计算机考研拟录取名单,北京邮电大学研究生拟录取名单2021公示...
- PowerGUI错误-Microsoft SharePoint is not supported with version 4 of the Microsoft .Net Runtime
- 问题记录-笔记本HDMI外接2k显示器如何调2k分辨率
- JAVA通过tcp通信劳易测BCL 308i扫码枪获取数据
- 保护环境的画用计算机怎么画,保护环境的简笔画图片大全
热门文章
- 苹果应用备份到电脑 苹果应用备份到新苹果手机
- MIUI10.3及以上最新版本 冰箱Ice Box的激活
- UG NX 12 如何确定绘制的草图是封闭的?
- [热血三国]七天称雄攻略
- 无语的IIS7...
- Android高仿微信照片选择器+预览+显示照片
- 黑洞引擎 mysql_MySql-BlackHole:黑洞引擎
- java计算机毕业设计课题申报系统源码+mysql数据库+系统+lw文档+部署
- 数据加密---之KMS
- 【JavaWeb】解决cookie跨域访问