一丶首先服务端的代码:
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8") ;
response.setContentType("text/html;charset=UTF-8") ;
PrintWriter out = response.getWriter() ;
try {
//1.指定上传的目录
String storeDirectory = getServletContext().getRealPath("/WEB-INF" + File.separator + "files") ;
//2.判断目录不存在则创建出来
File file = new File(storeDirectory) ;
if(!file.exists())
file.mkdirs() ;
//3. 创建上传的servletFileuload类
DiskFileItemFactory dif = new DiskFileItemFactory() ; //使用默认的临时目录
ServletFileUpload sfu = new ServletFileUpload(dif) ;
//多判断一步
boolean isMultipart = sfu.isMultipartContent(request) ;
if(!isMultipart){
out.write("上传的enctype必须是multipart/form-data类型") ;
return ;
}
//String newDirectory = makeNewDirectory(storeDirectory);
//设置单个文件的上传大小(限制上传文件的大小不的超过2M)
// sfu.setFileSizeMax(2*1024*1024) ;
//设置上传总文件的大小(限制上传文件的总的大小不的超过10M))
// sfu.setSizeMax(10*1024*1024) ;
//4. 解析请求
List<FileItem> items = sfu.parseRequest(request) ;
//5.判断是普通字段还是上传字段,分别处理
for (FileItem item : items) {
//依次判断
if(item.isFormField()){
//说明是普通字段
String name = item.getFieldName() ; //拿到文本框的名字
String value = item.getString("UTF-8") ; //拿到文本框中的内容
System.out.println(name + "=" + value);
}else{
//说明是上传字段
//限定上传的文件只能是图片
// if(item.getContentType().contains("p_w_picpath")){
//说明上传的是图片
//拿到上传的文件的名字
String filename = item.getName() ; //拿到文件名 :不包括路径
//如果文件名不是""则上传
System.out.println("上传文件名;" + filename);
//if("".equals(filename)){
filename = UUID.randomUUID() + "_" + filename ;
//采用文件名的hashcode计算目录名
String newDirectory = makeNewDirectory(storeDirectory,filename);
//System.out.println("filename:" + filename);
//System.out.println("aaaa:" + (storeDirectory + File.separator + newDirectory + File.separator + filename));
//构建服务器上的文件
File f = new File(storeDirectory + File.separator + newDirectory + File.separator + filename) ;
item.write(f) ;
//}
// }else{
// out.write("只能上传图片") ;
// return ;
// }
}
}
out.write("上传成功") ;
}catch (FileUploadBase.FileSizeLimitExceededException e1) {
out.write("上传文件不得大于2M") ;
}catch (FileUploadBase.SizeLimitExceededException e1) {
out.write("上传总文件不得大于10M") ;
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//用文件名的hashcode计算文件目录
private String makeNewDirectory(String storeDirectory,String filename) {
//拿到哈希码
int hashcode = filename.hashCode() ;
int dir1 = hashcode&0xf;
int dir2 = (hashcode&0xf0)>>4;
String newDirectory = File.separator + "" + dir1 + File.separator + dir2 ;
System.out.println(newDirectory);
//判断目录是否存在
File fdate = new File(storeDirectory,newDirectory) ;
System.out.println("bb:" +fdate.getAbsolutePath());
if(!fdate.exists())
fdate.mkdirs() ;
return "" + dir1 + File.separator + dir2 ;
}
//创建日期目录
private String makeNewDirectory(String storeDirectory) {
Date now = new Date() ;
String newDirectory = new SimpleDateFormat("yyyyMMdd").format(now) ;
File fdate = new File(storeDirectory,newDirectory) ;
if(!fdate.exists())
fdate.mkdirs() ;
return newDirectory;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Content-Type", "text/html;charset=UTF-8");
doGet(request, response);
}
}
二丶android上传代码:使用API中的AsyncHttpClient连接服务器
public void click(View view){
//拿到上传文件的路径
String path = etpath.getText().toString().trim() ;
//判断路径
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "路径不能为空", 0).show() ;
return ;
}
try {
//连接服务器,上传文件
String serverPath = "http://192.168.1.184:8080/upload/servlet/UploadServlet" ;
//创建连接对象
AsyncHttpClient http = new AsyncHttpClient() ;
//设置提交的数据
RequestParams params = new RequestParams() ;
params.put("file", new File(path)) ;
//发送post请求
http.post(serverPath, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers,
String content) {
super.onSuccess(statusCode, headers, content);
Toast.makeText(MainActivity.this, "上传文件成功", 0).show() ;
}
}) ;
} catch (Exception e) {
e.printStackTrace();
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。