robert_hly

踩坑填坑记录...

导航

java文件上传 关键代码

 文件上传
##前台:
form表单submit提交,form增加样式 enctype="multipart/form-data" method="post";
##后台
//String path为服务器保存文件的路径
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(5*1024);//缓存
factory.setRespository(new File(tempPath));//临时文件路径
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(8888*1024*1024);//设置最大

List<FileItem> items = upload.parseRequest(request);
FileItem item = items.get(i);
if(!item.isFormField()){
fileName = item.getName();            
String[] str = fileName.split("\\.");
String fileType = str[str.lenth-1];

InputStream in = item.getInputStream();//读取数据写入文件
FileOutputStream out = new FileOutputStream(path);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer,0len);
}
item.delete();
}

posted on 2017-07-23 22:04  robert_hly  阅读(192)  评论(0编辑  收藏  举报