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上传,会在下一篇博客中写。如有疑问联系[email protected]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。