Android上传图片,这里我使用了如今比較流行的XUtils框架。该框架能够实现文件上传、文件下载、图片缓存等等,有待研究。
以下是Android端上传的代码:
String uploadHost="http://192.168.1.100:8080/ReceiveImgFromAndroid/ReceiveImgServlet"; //server接收地址
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) {
//上传成功,这里面的返回值,就是server返回的数据
//使用 String result = responseInfo.result 获取返回值
}
@Override
public void onFailure(HttpException error, String msg) {
//上传失败
}
});
}
上面写完了手机端提交照片。接下来要写一个server端。
server端接收手机端上传照片的方法与接收jsp界面上传照片的方法同样。是用了jspsmartupload_zh.jar包文件。最简单的方式自己实现一个servlet,在里面调用SmartUpload类接收即可。这个还须要处理好接收文字的乱码问题。
以下是详细的代码:
SmartUpload.jar下载
server測试源代码下载
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();
} } }