转载请注明:Android使用XUtils框架上传照片(一张或多张)和文本,服务器使用struts2接收
Android上传图片还是使用的Xutils框架,只是在上传时拼成一定格式,方便服务器一次接收多张,之前服务器使用SmartUpload接收,只能在servlet中使用,现在服务器基本实现框架化,所以我也各方寻求帮助,终于找到Xutils和struts2配合使用的方法。这里struts2使用自带的接收文件的方法,写一个List<File>,然后生成get和set方法即可。
下面先看Android上传的代码:
private String uploadHost="http://192.168.1.100:8080/ReceiveImgFromAndroid/sendMessage_messageAction.action"; //服务器接收地址 private List<imgPath> imgList; //存放图片地址 RequestParams params=new RequestParams(); params.addBodyParameter("msg","上传图片"); for(int i = 0; i < imgList.size(); i++){ //这里拼成【attachment[i]】的形式,并加上【multipart/form-data】属性 params.addBodyParameter("attachment[" + i + "]", new File(imgList.get(i)), "multipart/form-data"); } sendImgToServer(params,uploadPath);
public void uploadMethod(final RequestParams params,final String uploadHost) { http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() { @Override public void onStart() { //上传开始 } @Override public void onLoading(long total, long current,boolean isUploading) { //上传中 } @Override public void onSuccess(ResponseInfo<String> responseInfo) { //上传成功,这里面的返回值,就是服务器返回的数据 //使用 String result = responseInfo.result 获取返回值 } @Override public void onFailure(HttpException error, String msg) { //上传失败 } }); }
public class MessageAction extends ActionSupport { private static final long serialVersionUID = 1L; HttpSession session = ServletActionContext.getRequest().getSession(); HttpServletResponse response = ServletActionContext.getResponse(); HttpServletRequest request = ServletActionContext.getRequest(); private List<File> attachment; private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<File> getAttachment() { return attachment; } public void setAttachment(List<File> attachment) { this.attachment = attachment; } //接收图片和文本 public String sendMessage() { String realPath = ServletActionContext.getServletContext().getRealPath( "/upload"); String msg = getMsg(); // 获取手机上传的文本 if (attachment != null && attachment.size() > 0) { for (int i = 0; i < attachment.size(); i++) { File src = attachment.get(i); File target = new File(realPath, System.currentTimeMillis()+".jpg"); //将图片重新命名 try { FileUtils.copyFile(src, target);//将接收到的图片拷贝到本地 } catch (IOException e) { e.printStackTrace(); } } } return SUCCESS; } }