概述
packagecom.servletdemo;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.PrintWriter;importjava.text.DateFormat;importjava.util.Date;importjava.util.List;importjava.util.UUID;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.FileUploadException;importorg.apache.commons.fileupload.ProgressListener;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;/*** Servlet implementation class UploadServlet*/@WebServlet("/servlet/UploadServlet")public class UploadServlet extendsHttpServlet {private static final long serialVersionUID = 1L;/***@seeHttpServlet#HttpServlet()*/
publicUploadServlet() {super();//TODO Auto-generated constructor stub
}/***@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//TODO Auto-generated method stub//设置编码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw=response.getWriter();try{//设置系统环境
DiskFileItemFactory factory = newDiskFileItemFactory();//文件存储的路径
String storePath = getServletContext().getRealPath("/WEB-INF/files");//判断传输方式 form enctype=multipart/form-data
boolean isMultipart =ServletFileUpload.isMultipartContent(request);if(!isMultipart)
{
pw.write("传输方式有错误!");return;
}
ServletFileUpload upload= newServletFileUpload(factory);
upload.setFileSizeMax(4*1024*1024);//设置单个文件大小不能超过4M
upload.setSizeMax(4*1024*1024);//设置总文件上传大小不能超过6M//监听上传进度
upload.setProgressListener(newProgressListener() {//pBytesRead:当前以读取到的字节数//pContentLength:文件的长度//pItems:第几项
public void update(long pBytesRead, longpContentLength,intpItems) {
System.out.println("已读去文件字节 :"+pBytesRead+" 文件总长度:"+pContentLength+" 第"+pItems+"项");
}
});//解析
List items =upload.parseRequest(request);for(FileItem item: items)
{if(item.isFormField())//普通字段,表单提交过来的
{
String name=item.getFieldName();
String value= item.getString("UTF-8");
System.out.println(name+"=="+value);
}else{//String mimeType = item.getContentType(); 获取上传文件类型//if(mimeType.startsWith("image")){
InputStream in =item.getInputStream();
String fileName=item.getName();if(fileName==null || "".equals(fileName.trim()))
{continue;
}
fileName= fileName.substring(fileName.lastIndexOf("\")+1);
fileName= UUID.randomUUID()+"_"+fileName;//按日期来建文件夹
String newStorePath =makeStorePath(storePath);
String storeFile= newStorePath+"\"+fileName;
OutputStream out= newFileOutputStream(storeFile);byte[] b = new byte[1024];int len = -1;while((len = in.read(b))!=-1)
{
out.write(b,0,len);
}
in.close();
out.close();
item.delete();//删除临时文件
}
}//}
}catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){//单个文件超出异常
pw.write("单个文件不能超过4M");
}catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){//总文件超出异常
pw.write("总文件不能超过6M");
}catch(FileUploadException e) {
e.printStackTrace();
}
}/***@seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//TODO Auto-generated method stub
doGet(request, response);
}privateString makeStorePath(String storePath) {
Date date= newDate();
DateFormat df=DateFormat.getDateInstance(DateFormat.MEDIUM);
String s=df.format(date);
String path= storePath+"\"+s;
File file= newFile(path);if(!file.exists())
{
file.mkdirs();//创建多级目录,mkdir只创建一级目录
}returnpath;
}privateString makeStorePath2(String storePath, String fileName) {int hashCode =fileName.hashCode();int dir1 = hashCode & 0xf;//0000~1111:整数0~15共16个
int dir2 = (hashCode & 0xf0) >> 4;//0000~1111:整数0~15共16个
String path= storePath + "\" + dir1 + "\" + dir2; //WEB-INF/files/1/12
File file = newFile(path);if (!file.exists())
file.mkdirs();returnpath;
}
}
最后
以上就是明理铃铛为你收集整理的java 上传下载demo_Java Servlet简单实例,文件上传下载demo的全部内容,希望文章能够帮你解决java 上传下载demo_Java Servlet简单实例,文件上传下载demo所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复