您的位置:首页 > 理论基础 > 计算机网络

Android基于http协议和httpClient上传文件

2014-03-20 22:34 405 查看
   在本文中,如果用HttpClient上传文件给We端是问题的,在调试中发现表单已提交成功,不过在后台却被判定为普通表单,因此没有保存到本地文件夹;拼接http报文提交表单是可用的,已测试成功。

web端用servlet和commons-fileupload框架:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name>
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.hj.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>*.swf</url-pattern>
</servlet-mapping>

<listener>
<listener-class>
org.apache.commons.fileupload.servlet.FileCleanerCleanup
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


后台源码:
package com.hj;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.persistence.Entity;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub

// 保存目录
String path = req.getSession().getServletContext().getRealPath("/")+"Image";
System.out.println(path);
// 目录是否存在
File filedir = new File(path);
if(!filedir.exists()){
filedir.mkdir();
}

// 为基于硬盘文件的项目集创建一个工厂
FileItemFactory factory = new DiskFileItemFactory();
// 创建一个新的文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析请求
try {
List items = upload.parseRequest(req);

Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

// 是否是普通表单
if (!item.isFormField()) {
String name=item.getName();
System.out.println(name);
name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名
File file = new File(path,name);

try {
item.write(file);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} else {

}
}
} catch (FileUploadException e) {

e.printStackTrace();
}

}

}


index.jsp:
<body>
<form id="form1" name="form2" method="post" action="file.swf" enctype="multipart/form-data" >
<input type="file" id="file" name="file" />
<input type="submit" id="submit" name="submit" value="提交" />
</form>
</body>

         下面是Android上传文件调用的方法
http协议:PS(拼接http报文实现,百度有关于http报文的详细解析)

public void uploadFile(String actionUrl,String srcPath)
{

String uploadUrl = "http://192.168.1.11:8080/web/file.swf";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; 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();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();

dos.close();
is.close();

} catch (Exception e)
{
e.printStackTrace();

}

}

HttpClient实现文件上传:
public void sendImage(String url,String path){

HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url);
File file = new File(path);

try {
InputStream fileInputStream = new FileInputStream(file);
InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, file.length());
reqEntity.setContentType("binary/octet-stream");
httpPost.setHeader( "Content-Type", "multipart/form-data;boundary="+"BOUNDARY");

httpPost.setEntity(reqEntity);

try {
HttpResponse response = null;
try{
response = httpClient.execute(httpPost);
}catch(Exception e){
Log.i("HttpResponse", "There Fail");
}
HttpEntity entity = response.getEntity();
if(entity!=null){
entity.consumeContent();
}
fileInputStream.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

httpClient.getConnectionManager().shutdown();
}

    代码都是参考百度谷歌进行了部分修改,如有错误还请不吝指出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  http协议 android upload