ANDROID批量文件上传(附Demo文件)
来源:互联网 作者:佚名 时间:2015-08-18 20:56
在最底层,java中的数据操作是通过使用操作符来
前言
此篇主要介绍android的批量文件上传(从相册选择图片并上传)。
客户端采用HttpClient和Http协议共2种上传方式。
服务端采用Spring MVC接收批量文件上传。
ANDROID客户端
1、HttpClient方式上传
准备文件
httpmime-4.1.1.jar (源码里面libs文件夹下)
代码中需要使用到此jar文件中的MultipartEntity类。这是Apache的一个jar包,不是android自带的。
代码
//网络请求需要开启新的线程,不能在主线程中操作
Runnable multiThread = new Runnable() {
@Override
public void run() {
try {
multiUploadFile1();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void multiUploadFile1 () throws UnsupportedEncodingException {
//HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//采用POST的请求方式
//这是上传服务地址:8080/WebAppProject/main.do?method=upload2
HttpPost httpPost = new HttpPost(":8080/WebAppProject/main.do?method=upload2");
//MultipartEntity对象,需要httpmime-4.1.1.jar文件。
MultipartEntity multipartEntity = new MultipartEntity();
//StringBody对象,参数
StringBody param = new StringBody("参数内容");
multipartEntity.addPart("param1",param);
//filesPath为List对象,里面存放的是需要上传的文件的地址
for (String path:filesPath) {
//FileBody对象,需要上传的文件
ContentBody file = new FileBody( new File(path));
multipartEntity.addPart("file",file);
}
//将MultipartEntity对象赋值给HttpPost
httpPost.setEntity(multipartEntity);
HttpResponse response = null;
try {
//执行请求,并返回结果HttpResponse
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//上传成功后返回
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("-->success");
} else {
System.out.println("-->failure");
}
}
};
运行很简单:
new Thread(multiThread).start();
2、HTTP协议上传
此种方式在网上也很多,下面的HTTP协议部分的代码是从网上Copy的。
public static String post(String path, Map params, FormFile[] files,Handler handler) throws Exception{
try {
final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
int fileDataLength = 0;//文件长度
for(FormFile uploadFile : files){//得到文件类型数据的总长度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if(uploadFile.getInStream()!=null){
if (uploadFile.getFile() != null) {
fileDataLength += uploadFile.getFile().length();
} else {
fileDataLength += uploadFile.getFileSize();
}
}else{
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry entry : params.entrySet()) {//构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
//计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString() .getBytes().length + fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort()==-1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
Log.i("hbgz", "socket connected is " + socket.isConnected());
OutputStream outStream = socket.getOutputStream();
//下面完成HTTP请求头的发送
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: "+ dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
outStream.write(host.getBytes());
//写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
//把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
int lenTotal = 0;
//把所有文件类型的实体数据发送出来
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
InputStream is = uploadFile.getInStream();
if(is!=null) {
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
lenTotal += len;//每次上传的长度
Message message = new Message();
message.arg1 = 11;
message.obj = lenTotal;
handler.sendMessage(message);
}
is.close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
//下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "";
boolean requestCodeSuccess = false;
boolean uploadSuccess = false;
int indexResult = 1;
while((str = reader.readLine()) != null) {
Log.d("yjw", "upload--->str=" + str);
if (indexResult == 1) {
if (str.indexOf("200") > 0) {
requestCodeSuccess = true;
}
}
if (indexResult == 6) {
if ("true".equals(str.trim())) {
uploadSuccess = true;
}
}
if (requestCodeSuccess && uploadSuccess) {
outStream.flush();
if(null != socket && socket.isConnected())
{
socket.shutdownInput();
socket.shutdownOutput();
}
outStream.close();
reader.close();
socket.close();
return str.trim();
} else if (indexResult == 6) {
outStream.flush();
if(null != socket && socket.isConnected())
{
socket.shutdownInput();
socket.shutdownOutput();
}
outStream.close();
reader.close();
socket.close();
return str.trim();
}
++indexResult;
}
outStream.flush();
if(null != socket && socket.isConnected())
{
socket.shutdownInput();
socket.shutdownOutput();
}
outStream.close();
reader.close();
socket.close();
return null;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}