使用httpclient模拟表单上传文件,后台用struts2接收

来源:互联网 发布:嵌入式开发编程 编辑:程序博客网 时间:2024/06/18 10:47

本人是使用java,开发android后台的,公司要求使用SSM框架,有一个功能要求是实现android大文件的上传。开发人员都是新手,以前没有开发经验,鼓捣了好久,也尝试了两个android框架,Xutils貌似跟struts2不太好整合,而AsyncHttpClient则遇到莫名奇妙的bug。后来本人查了很多资料,最后决定用httpclient模拟表单上传。

下面直接上代码

客户端部分:

public class HttpClientUpload{/** *使用httpclient模拟form表单上传文件 * @param url 文件上传的目标地址 * @param filepath 要上传的文件路径 * @param mapParams 文字参数(采用键值对应) */public static void upload(String url, String filepath,HashMap<String, String> mapParams) {HttpClient client = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");try {MultipartEntity entity = new MultipartEntity();//多个表单对象ContentBody fileBody = new FileBody(new File(filepath)); //表单文件域entity.addPart("upload", fileBody);    entity.addPart("path", new StringBody(mapParams.get("savePath")));// 字符参数部分httpPost.setEntity(entity);HttpResponse response = client.execute(httpPost);//执行post操作,并返回responseString jsonData = EntityUtils.toString(response.getEntity(), "UTF-8");System.out.println(jsonData);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {String url ="http://localhost:8080/GoApp/uploadPro.action";String filepath="C:\\Users\\Administrator\\Desktop\\test.mkv";HashMap<String, String> mapParams = new HashMap<String, String>();mapParams.put("savePath", "\\gaopenghui");upload(url,filepath,mapParams);}}
struts2的action配置:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts><constant name="struts.i18n.encoding" value="utf-8" /><constant name="struts.multipart.maxSize" value="60000000" /><package name="struts2-message" extends="struts-default,json-default"><action name="uploadPro" class="com.eagle.message.action.UploadAction"method="upload"><!-- 默认的拦截器,必须要写 --><interceptor-ref name="fileUpload"><param name="maximumSize">42830000</param></interceptor-ref><interceptor-ref name="defaultStack" /><param name="savePath">/upload</param><result type="json"></result></action></package></struts>

action的处理部分:

package com.eagle.message.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport {/** *  */private static final long serialVersionUID = 1L;private String path;private File upload;private String uploadContentType;private String uploadFileName;private String savePath;private HttpServletResponse response;public String getPath() {return path;}public void setPath(String path) {this.path = path;}@SuppressWarnings("deprecation")public String getSavePath() {return ServletActionContext.getRequest().getRealPath(savePath);}public void setSavePath(String savePath) {this.savePath = savePath;}public String getTitle() {return path;}public void setTitle(String title) {this.path = title;}public File getUpload() {return upload;}public void setUpload(File upload) {this.upload = upload;}public String getUploadContentType() {return uploadContentType;}public void setUploadContentType(String uploadContentType) {this.uploadContentType = uploadContentType;}public String getUploadFileName() {return uploadFileName;}public void setUploadFileName(String uploadFileName) {this.uploadFileName = uploadFileName;}/** * 返回json数据的方法 *  * @param json *            要发送的数据 */public void response(String json) {response = ServletActionContext.getResponse();response.setContentType("application/json;charset=utf-8");try {PrintWriter out = response.getWriter();out.print(json);out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}/** * 响应上传文件请求的action方法 */public void upload() {File file = new File(getSavePath() + path);if (!file.exists()) {// 若文件目录不存在,则创建目录file.mkdirs();}try {FileOutputStream fos = new FileOutputStream(getSavePath() + path+ "\\" + uploadFileName);FileInputStream fis = new FileInputStream(getUpload());byte[] buffer = new byte[1024];int len = 0;while ((len = fis.read(buffer)) > 0) {fos.write(buffer, 0, len);}setUploadFileName(uploadFileName);fos.close();fis.close();} catch (Exception e) {response("文件上传失败");e.printStackTrace();return;}response("文件上传成功");}}

struts2默认使用Jakarta的Common-FileUpload文件上传框架,它可以将表单发送来的数据进行封装,如action中的upload对应表单中的upload域,而path对应表单中的path域,除此之外action中还有uploadContentType封装了上传文件的文件类型,uploadFileName封装了上传文件的文件名(包括文件类型在内,如test.jpg)。

这是本菜鸟的第一篇博文,希望对大家有所帮助。

httpclient要用到的jar包如图所示:




1 0
原创粉丝点击