Android上传图片,这里我使用了现在比较流行的XUtils框架,该框架可以实现文件上传、文件下载、图片缓存等等,有待研究。
下面是Android端上传的代码:
xUtils.jar下载
String uploadHost="http://192.168.1.100:8080/ReceiveImgFromAndroid/ReceiveImgServlet"; //服务器接收地址 RequestParams params=new RequestParams(); params.addBodyParameter("msg","上传图片"); params.addBodyParameter("img1", new File(filePath)); //filePath是手机获取的图片地址 sendImgToServer(params,uploadPath);这是Xutils框架中上传文件的方法:
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) { //上传失败 } }); }上面写完了手机端提交照片,接下来要写一个服务器端。
服务器端接收手机端上传照片的方法与接收jsp界面上传照片的方法相同,是用了jspsmartupload_zh.jar包文件。最简单的方式自己实现一个servlet,在里面调用SmartUpload类接收就行,这个还需要处理好接收文字的乱码问题。
下面是具体的代码:
SmartUpload.jar下载 服务器测试源码下载
package com.example.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; /** * 接收图片 * * @author Administrator * @time 2015年8月10日09:27:17 */ public class ReceiveImgServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); SmartUpload smartUpload = new SmartUpload(); try { smartUpload.initialize(this.getServletConfig(), request, response); smartUpload.upload(); String msg = smartUpload.getRequest().getParameter("msg"); if (msg != null) msg = new String(msg.getBytes("GBK"), "utf-8"); com.jspsmart.upload.Files files = smartUpload.getFiles(); for (int i = 0; i < files.getCount(); i++) { com.jspsmart.upload.File file = files.getFile(i); if (!file.isMissing()) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS"); String name = sdf.format(new java.util.Date()); name = name + "." + file.getFileExt();// 得到文件的扩展名 String filename = this.getServletContext().getRealPath("/") + "images\\" + name; file.saveAs(filename); } } } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }