天天看点

android上传本地图片到服务器,Android 图片上传 服务器端(一)

直接上浏览器端upload.jsp代码(为测试服务器端)

pageEncoding="utf-8"%>

upload

Name
Gender
请选择一个上传文件

注意enctype="multipart/form-data" (复杂的数据提交)和{pageContext.request.contextPath}/upload.do工程访问路径

还有就是字符集统一使用utf-8 小心中文乱码。

2.服务器端,采用commons-fileupload  来实现文件上传,仍然使用Servlet

commons-fileupload-1.3.1.jar+ commons-io-2.4.jar(本人出现兼容报错)

代码如下

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

//判断是否是复杂表单提交

boolean isMutipart=ServletFileUpload.isMultipartContent(request);

//

if(isMutipart)

{

//配置缓存工厂

DiskFileItemFactory factory=new DiskFileItemFactory();

//设置缓存大小

factory.setSizeThreshold(1024*1024*2);

File temp=new File("D:\\temp");

if (!temp.exists()) {

temp.mkdir();

}

factory.setRepository(temp);

ServletFileUpload upload=new ServletFileUpload(factory);

// upload.setHeaderEncoding("utf-8");

upload.setFileSizeMax(1024*1024*5);

upload.setSizeMax(1024*1024*6);

//获取提交的集合

try {

Listitems=upload.parseRequest(request);

if(items!=null)

{

for(FileItem item :items)

{

if(item.isFormField())

{

//一般数据

System.out.println(item.getFieldName());

System.out.println(item.getString("utf-8"));

}

else {

String pathString=item.getName();

if(pathString.contains("\\"))

{

int index=pathString.lastIndexOf("\\");

pathString=pathString.substring(index+1);

}

System.out.println(pathString);

//复杂文件

try {

item.write(new File("D:\\"+pathString));

response.getWriter().write("upload success!");

} catch (Exception e) {

e.printStackTrace();

response.getWriter().write("upload fail.");

}

}

}

}

} catch (FileUploadException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

else {

return;

}

}

传送门:

[rar文件] andriod、iOS服务器端代码之文件上传