android手机上传文件:
1.准备三个jar包
"commons-codec-1.3.jar"、"commons-httpclient-3.1.jar"、"commons-logging-1.1.jar"
2.手机端代码实现
//打开一个浏览器
HttpClient client = new HttpClient();
//访问的路径
PostMethod post = new PostMethod(
"http://192.168.1.135:8080/LoginWeb/servlet/UploadServlet");
try {
String path = et_path.getText().toString().trim();
File file = new File(path);
if (file.exists() && file.length() > 0) {
//上传的字段
Part[] parts = { new StringPart("aaaa", "111"),//普通字段,相当于表单中的普通字段
new FilePart("picc", new File(file.getAbsolutePath())) };//上传字段,相当于表单中的上传字段
//设置请求实体
post.setRequestEntity(new MultipartRequestEntity(parts, post
.getParams()));
//设置超时时间
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status = client.executeMethod(post);
if (status == 200) {
Toast.makeText(this, "上传成功", 1).show();
} else {
Toast.makeText(this, "上传失败", 1).show();
}
} else {
Toast.makeText(this, "上传的文件不存在", 0).show();
}
} catch (Exception e) {
e.printStackTrace();
post.releaseConnection();
}
3.服务器端代码实现:准备jar包:"commons-fileupload-1.2.2.jar"和"commons-io-1.4.jar"
//判断客户端提交的表单是否是“multipart/form-data”形式提交的的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
//获取上传的文件存储在web应用的哪里
String realpath = request.getSession().getServletContext()
.getRealPath("/files");
//E:\AppData\tomcat\apache-tomcat-6.0.36\webapps\LoginWeb\files
System.out.println(realpath);
File dir = new File(realpath);
if (!dir.exists())
dir.mkdirs();
//创建一个文件条目解析工厂,用于下面创建ServletFileUpload的一个对象
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
//普通字段
if (item.isFormField()) {
String name1 = item.getFieldName();// 得到请求参数的名称
String value = item.getString("UTF-8");// 得到参数值
System.out.println(name1 + "=" + value);//aaaa=111
} else {
//上传字段
//将上传的内容写到web应用的指定目录下
item.write(new File(dir, System.currentTimeMillis()
+ item.getName().substring(
item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
doGet(request, response);
}
附加代码:javaweb详细服务器端获取客户端(浏览器)上传的文件:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
try{
request.setCharacterEncoding("utf-8");
//得到上传文件要存储的真实路径
String realPath = getServletContext().getRealPath("/WEB-INF/files");
//得到DiskFileItemFactory的一个实例
DiskFileItemFactory factory=new DiskFileItemFactory();
//自定义临时目录
factory.setRepository(new File(getServletContext().getRealPath("/temp")));
//利用得到的factory创建一个ServletFileUpload的一个实例
ServletFileUpload upload=new ServletFileUpload(factory);
//判断form表单是否以“multipart/form-data”形式提交的数据
boolean isMultipart = upload.isMultipartContent(request);
if(!isMultipart){
return ;
}
//设置单个文件上传的大小
upload.setFileSizeMax(5*1024*1024);
//设置总共文件上传大小
upload.setSizeMax(10*1024*1024);
//对HttpServletRequest进行解析,得到一个list对象
List<FileItem> items = upload.parseRequest(request);
//对items进行遍历,判断是否是普通字段还是上传字段
for(FileItem item:items){
if(item.isFormField()){
//普通字段
String fieldName=item.getFieldName();
String value=item.getString("utf-8");
System.out.println("普通字段:"+fieldName+"="+value);
}else{
//上传字段
//限制上传文件只能是图片
String contentType = item.getContentType();
System.out.println("contentType..."+contentType);
if(!contentType.startsWith("image/")){
throw new RuntimeException("上传的文件只能是图片");
}
//得到输入流
InputStream in = item.getInputStream();
//得到上传文件的名称--》绝对路径
String path = item.getName();
System.out.println("上传字段:"+path);
path=path.substring(path.lastIndexOf("\\")+1);
System.out.println("切割后"+path);
if("".equals(path)){
continue;
}
//创建一个输出流,将文件写道指定的目录下
path=UUID.randomUUID().toString()+"_"+path;
String mulitPath=makeDir(realPath,path);
OutputStream out=new FileOutputStream(mulitPath+"\\"+path);
//开始写数据
int len=-1;
byte[] buf=new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
item.delete();
}
}
}catch(FileUploadBase.SizeLimitExceededException e){
response.getWriter().write("总文件文件不能超过10M大小");
}catch(FileUploadBase.FileSizeLimitExceededException e){
response.getWriter().write("单个文件不能超过5M大小");
}catch(Exception e){
e.printStackTrace();
}
}
private String makeDir(String realPath, String path) {
int hashCode=path.hashCode();
int path1=hashCode&0xf;
int path2=(hashCode&0xf0)>>4;
String newPath=realPath+"\\"+path1+"\\"+path2;
File file=new File(newPath);
if(!file.exists()){
file.mkdirs();
}
return newPath;
}
- 1
- 2
- 3
- 4
- 5
前往页