实例介绍
android手机端上传文件到服务器端 ,包括源代码,手机端和服务器端javaweb(Tomcat)
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;
}
【实例截图】
标签:
相关软件
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论