package com.itheima.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils; import com.itheima.util.IdGenertor; public class UploadServlet3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); //检测form是否是multipart/form-data类型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("The form's enctype attribute value must be multipart/form-data");
}
//解析请求内容
DiskFileItemFactory factory = new DiskFileItemFactory();//产生FileItem的工厂
factory.setRepository(new File("d:/"));//指定临时文件的存放目录
ServletFileUpload sfu = new ServletFileUpload(factory); // sfu.setFileSizeMax(3*1024*1024);//单个文件大小限制
// sfu.setSizeMax(5*1024*1024);//总文件大小 List<FileItem> items = new ArrayList<FileItem>();
try {
items = sfu.parseRequest(request);
}catch(FileUploadBase.FileSizeLimitExceededException e) {
response.getWriter().write("单个文件不能超过3M");
}
catch(FileUploadBase.SizeLimitExceededException e) {
response.getWriter().write("总文件不能超过5M");
}catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("解析请求失败");
}
//遍历:
for(FileItem item:items){
//处理普通字段
if(item.isFormField()){
processFormField(item);
}else{
//处理上传字段
processUploadField(item);
}
}
} protected void processUploadField(FileItem item) {
try { // InputStream in = item.getInputStream();
//找一个存放文件的位置;存放的文件名
String fileName = item.getName();//上传的文件的文件名 C:\Users\wzhting\Desktop\a.txt a.txt(浏览器不同)
if(fileName!=null&&!fileName.equals("")){ //限定上传文件的类型
if(!item.getContentType().startsWith("image")){
return;
} fileName = FilenameUtils.getName(fileName);
fileName = IdGenertor.genGUID()+"_"+fileName; //存放路径
String realPath = getServletContext().getRealPath("/WEB-INF/files"); //生成一个子目录
String childDirectory = genChildDirectory(realPath,fileName); File storeDirectory = new File(realPath+File.separator+childDirectory);
if(!storeDirectory.exists()){
storeDirectory.mkdirs();
}
// OutputStream out = new FileOutputStream(new File(storeDirectory, 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(storeDirectory, fileName));
} } catch (Exception e) {
e.printStackTrace();
}
}
private String genChildDirectory(String realPath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode&0xf;
int dir2 = (hashCode&0xf0)>>4; String str = dir1+File.separator+dir2; File file = new File(realPath,str);
if(!file.exists()){
file.mkdirs();
} return str; } //按照日期生成子目录
private String genChildDirectory(String realPath) {
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String str = df.format(now); File file = new File(realPath,str);
if(!file.exists()){
file.mkdirs();
} return str;
} protected void processFormField(FileItem item) {
//打印到控制台
String fieldName = item.getFieldName();
String fieldValue = "";
try {
fieldValue = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(fieldName+"="+fieldValue);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

  

FileUpload组件的更多相关文章

  1. .JavaWeb文件上传和FileUpload组件使用

    .JavaWeb文件上传 1.自定义上传 文件上传时的表单设计要符合文件提交的方式: 1.提交方式:post 2.表单中有文件上传的表单项:<input type="file" ...

  2. Primefaces的fileUpload组件使用

    最近在学习Primefaces(当然也是项目中需要用的).在使用其fileUpload遇到了不小的困难,现总结一下供大家及我自己今后参考使用. 1.首先是使用环境配置:正常的Primefaces开发环 ...

  3. 文件上传使用FileUpload组件进行代码实现

    使用FileUpload组件进行代码实现 实现步骤 1. 获取解析器工厂: DiskFileItemFactory 2. 获取解析器对象: ServletFileUpload 3. 解析request ...

  4. 实现文件上传功能(FileUpload组件)

    文件上传: 项目中经常用到文件上传. 自己实现文件上传,使用文件上传组件fileupload组件 1.指定表单类型为文件上传, enctype=”multipart/form-data” 2.提交方式 ...

  5. 使用 fileupload 组件完成文件的上传应用

    1. 使用 fileupload 组件完成文件的上传应用 commons-dbutils-1.3.jarcommons-fileupload-1.2.1.jar 1). 需求: > 在 uplo ...

  6. JSP文件上传--FileUpload组件

    如果使用上传操作,并且没有使用框架之类,最好使用Smartupload,因为FileUpdate太难使用. 下载组件: fileupload包:http://commons.apache.org/pr ...

  7. 使用fileupload组件

    1. 进行文件上传时, 表单需要做的准备: 1). 请求方式为 POST: <form action="uploadServlet" method="post&qu ...

  8. 模拟文件上传(三):使用apache fileupload组件进行文件批量上传

    其中涉及到的jar包 jsp显示层: <%@ page language="java" import="java.util.*" pageEncoding ...

  9. 模拟文件上传(二):使用apache fileupload组件进行文件上传

    其中涉及到的jar包: jsp显示层: <%@ page language="java" import="java.util.*" pageEncodin ...

随机推荐

  1. BZOJ4078 : [Wf2014]Metal Processing Plant

    设$D(A)\leq D(B)$,从小到大枚举$D(A)$,双指针从大到小枚举$D(B)$. 那么对于权值不超过$D(A)$的边,可以忽略. 对于权值介于$(D(A),D(B)]$之间的边,需要满足那 ...

  2. Leetcode Divide Two Integers

    Divide two integers without using multiplication, division and mod operator. 不用乘.除.求余操作,返回两整数相除的结果,结 ...

  3. Fouandation(NSString ,NSArray,NSDictionary,NSSet) 中常见的理解错误区

    Fouandation 中常见的理解错误区 1.NSString //快速创建(实例和类方法) 存放的地址是 常量区 NSString * string1 = [NSString alloc]init ...

  4. wordpress 安装 "Table Prefix" must not be empty.

    时隔一年了,一年没有写代码了.又重拾代码,心情无法言表啊.互联网还是有机会的. 安装wordpress怎么装 setp2了就 报 "Table Prefix" must not b ...

  5. H TC並沒有成為下一個摩托羅拉或諾基亞。

    關於2014年第四季度,H T C在三季度財報說明中提到,“年度旗艦H T CO ne(M 8)與中端機型H T C D esire系列在競爭日趨激烈的智能手機市場保持穩定的銷售,市占率有所提升,延續 ...

  6. jQuery 中的事件冒泡和阻止默认行为

    1.事件冒泡 <%@ page language="java" import="java.util.*" pageEncoding="utf-8 ...

  7. MySQL数据的主从复制、半同步复制和主主复制详解

    一.MySQL复制概述 ⑴.MySQL数据的复制的基本介绍 目前MySQL数据库已经占去数据库市场上很大的份额,其一是由于MySQL数据的开源性和高性能,当然还有重要的一条就是免费~不过不知道还能免费 ...

  8. T2 Func<in T1,out T2>(T1 arg)

    委托调用方法的4种方式. using System; using System.Collections.Generic; namespace ConsoleApplication1 { delegat ...

  9. springboot+redis

    上篇整合了DB层,现在开始整合缓存层,使用redis. springboot驱动注解,使用spring注入JedisPool便可封装自己的redis工具类. package hello.configu ...

  10. [不好分类]SD卡无法读取,显示RAW

    上周同事拿来了一个8G的SD卡,插入读卡器后显示“需要格式化”.无法读取.文件格式处显示“RAW”,磁盘大小显示0字节. 处理步骤如下: 1.按照提示,格式化,选择“快速格式化”. 2.采用数据恢复软 ...