android上传图片到服务器很常用到,例如上传头像,发表带照片的帖子之类。
首先讲服务器端,服务器端用java,只上传头像在此只用Servlet说明,暂不使用框架。
public class UpLoadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imagePath = "/headImgs";
request.setCharacterEncoding("utf-8"); //设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获取文件需要上传到的路径
String requestPath = request.getServletContext().getRealPath(imagePath);
String realPath = "E:\\headImgs";//realPath是指图片上传的真实路径
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
//设置临时文件夹
factory.setRepository(new File(realPath));
//设置 缓存的大小
factory.setSizeThreshold(1024*1024);
//文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上传多个文件
List list = (List)upload.parseRequest(new ServletRequestContext(request));
for(FileItem item : list){
//获取属性名字
String name = item.getFieldName();
//如果获取的 表单信息是普通的 文本 信息
if(item.isFormField()){
//获取用户具体输入的字符串,因为表单提交过来的是 字符串类型的
String value = item.getString() ;
request.setAttribute(name, value);
}else{ //如果是文件等之类
//获取路径名
String value = item.getName() ;
//索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start+1);
request.setAttribute(name, filename);
//写到磁盘上
item.write( new File(realPath,filename) );
//返回客户端
String returnImgPath = imagePath +"/"+filename;
returnImgPath = returnImgPath.substring(1, returnImgPath.length());//去除第一个斜杠
System.out.println("上传成功:" + returnImgPath);
response.getWriter().print(returnImgPath);//将路径返回给客户端
}
}
} catch (Exception e) {
System.out.println("上传失败");
response.getWriter().print("上传失败:"+e.getMessage());
}
}
}
这里比较难理解的是路径的问题,这里我是用了虚拟路径,虚拟路径的配置请看
eclipse配置上传文件的虚拟路径(多坑版) 。最后返回图片的路径用于给客户端显示
客户端Android: 使用okHttp
private void upLoadImageToServer() {
String headImgName = "header.jpg";
OkHttpUtils.post()
.addFile("mFile", headImgName, imageFile)
.url(Config.UPLOAD_HEAD_IMG_URL)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
mImageUrl = Config.LOGIN_URL + response;
}
});
}
使用okHttp上传文件,使用的是表单上传的方式 -- addFile()中,第一个参数是文件的name,相当于web表单上传的input的name,第二个参数是文件的实际名称,这里我取得是head.jpg,第三个是文件。
以上步骤就能把文件(图片)上传完毕了
其实主要在于服务端。