commons-fileupload上传下载文件

来源:互联网 发布:郑州自学考试网络报名 编辑:程序博客网 时间:2024/06/05 18:21
public class UploadServlet1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletInputStream in = request.getInputStream();//获取请求正文的输入流
int len = -1;
byte b[] = new byte[1024];
while((len=in.read(b))!=-1){
System.out.println(new String(b,0,len));
}
in.close();

}


private void test1(HttpServletRequest request) {
/*
request.getParameter(String paramName)
只能获取请求正文为application/x-www-form-urlencoded类型的数据

name=abc&password=123
*/


String name = request.getParameter("name");
String photo = request.getParameter("photo");
System.out.println("name:"+name);
System.out.println("photo:"+photo);//不靠谱
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

------------------------------------------------------------------------------------------------------------------------------


public class UploadServlet2 extends HttpServlet {
protected String storeDirectoryRealPath;//存放文件目录的真实路径
//获取初始化参数:上传文件的存放目录
public void init() throws ServletException {
String storeDirectory = "/upload";//默认的存放上传文件的位置
String value = getServletContext().getInitParameter("storeDirectory");
if(value!=null){
storeDirectory = value;
}
//该目录可能不存在
//得到文件的真实路径
storeDirectoryRealPath = getServletContext().getRealPath(storeDirectory);
//判断文件夹是否存在,不存在,创建它
File directory = new File(storeDirectoryRealPath);
if(!directory.exists())
directory.mkdirs();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断用户的请求内容是否是mutlipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("not a file upload request");
}
try {
//创建DiskFileItemFactory,并设置缓存和临时文件的存放目录
DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setRepository(new File("d:/"));

//创建ServletFileUpload, 核心解析类
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setProgressListener(new ProgressListener() {
// /**
// * pBytesRead:已经读取的字节数
// * pContentLength:总上传文件的大小
// * pItems:当前处理的表单项
// */
// public void update(long pBytesRead, long pContentLength, int pItems) {
//// double d = (pBytesRead+0.0)/pContentLength;
// System.out.println(pBytesRead+">>>"+pContentLength+">>"+pItems);
// }
// });

// upload.setFileSizeMax(2*1024*1024);//设置单文件大小
// upload.setSizeMax(3*1024*1024);//设置总文件大小
//得到了List<FileItem>
List<FileItem> items = upload.parseRequest(request);
//遍历:
for(FileItem item:items){
//遇到普通字段:做出自己的处理
if(item.isFormField()){
processFormField(item);
}else{
//遇到上传字段:实现文件的上传

String mimeType = item.getContentType();//获取上传输入域的MIME类型
if(!mimeType.startsWith("image")){
//日志记录一下
continue;
}
processUploadField(item);
}
}
response.getWriter().write("上传成功!");
}catch(FileUploadBase.FileSizeLimitExceededException e) {
response.getWriter().write("单文件不能超过2M");
}catch(FileUploadBase.SizeLimitExceededException e){
response.getWriter().write("总文件不能超过3M");
}catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("解析请求内容时遇到了错误");
}

}
//处理上传文件
protected void processUploadField(FileItem item) {
try {
//获取输入流
// InputStream in = item.getInputStream();
//得到上传文件的文件名
String fileName = getFileName(item.getName());//  浏览:C:\Users\wzhting\Desktop\a.txt   浏览器:a.txt
//构建输出流
// OutputStream out = new FileOutputStream(storeDirectoryRealPath+"/"+fileName);
// int len = -1;
// byte b[] = new byte[1024];
// while((len=in.read(b))!=-1){
// out.write(b, 0, len);
// }
// in.close();
// out.close();
// item.delete();//删除临时文件
item.write(new File(storeDirectoryRealPath+"/"+fileName));

} catch (IOException e) {
throw new RuntimeException("读取上传文件出错");
}catch(Exception e){
throw new RuntimeException("写文件出错");
}

}
/**
* 如果文件路径是whole path,截取文件名
* @param fileName
*/
protected String getFileName(String fileName) {
if(fileName.indexOf("\\")!=-1){
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
}
return fileName;
}
//处理普通字段内容
protected void processFormField(FileItem item) {
String fieldName = item.getFieldName();//普通字段名
String fieldValue = item.getString();//普通字段值
System.out.println(fieldName+"="+fieldValue);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

---------------------------------------------------------------------------------------------------------------------------------------

protected void processFormField(FileItem item) {
String fieldName = item.getFieldName();//普通字段名
String fieldValue;
try {
fieldValue = item.getString("UTF-8");//普通字段值,指定编码,该编码和浏览器使用的编码要对应
System.out.println(fieldName+"="+fieldValue);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


//按照日期分目录存储文件
// protected String getFileName(String fileName) {
// String name = super.getFileName(fileName);// a.txt
// //按照日期创建目录
// Date now = new Date();
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// String date = df.format(now);
// //拼接该目录的真实存放路径
// String directoryPath = storeDirectoryRealPath+"/"+date;
// File directory = new File(directoryPath);
// if(!directory.exists())
// directory.mkdirs();
//
// return date+"/"+UUID.randomUUID().toString()+"_"+name;
// }
//按照UUID文件名的hashCode计算存放目录
protected String getFileName(String fileName) {
String name = super.getFileName(fileName);// a.txt
String uuidFileName = UUID.randomUUID().toString()+"_"+name;// ae427cfa-4920-418a-992a-59553e54a302_a.txt

/*
hashCode:
1001 1100 0101 1010 1111 0001
0000 0000 0000 0000 0000 1111  &0xf
-----------------------------------
0000 0000 0000 0000 0000 0001    取hash码的最低4位:0000~1111 十进制:0~15
hashCode:
1001 1100 0101 1010 1111 0001
0000 0000 0000 0000 1111 0000 &0xf0
-----------------------------------
0000 0000 0000 0000 1111 0000  取hash码的最低5~8位
-----------------------------------
>>4
0000 0000 0000 0000 0000 1111:0000~1111 十进制:0~15
*/

int hashCode = uuidFileName.hashCode();
int dir1 = hashCode&0xf;//一级目录
int dir2 = (hashCode&0xf0)>>4;//二级目录

String newPath = dir1+"/"+dir2;
String directoryPath = storeDirectoryRealPath+"/"+newPath;
File directory = new File(directoryPath);
if(!directory.exists())
directory.mkdirs();

return newPath+"/"+uuidFileName;
}

0 0
原创粉丝点击