FlieUpload文件上传

基于FlieUpload组件的文件上传
直接上代码

现在导入FileUpload组件的jar包 下载

  1. jsp页面编写
    注意点:
    (1)提交方式必须为post、
    (2)enctype的属性必须为multipart/form-data
<form action="${pageContext.request.contextPath}/FileController" method="Post" enctype="multipart/form-data">
	
		<input type="file" name="files"/>
		<input type="submit" value="提交"/>
	</form>

2.servlet处理类

@WebServlet("/FileController")
public class FileController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public FileController() {
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/** 处理上传文件 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		// 设置编码格式
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 先判断单位文件是否符合文件上传
		boolean isUpload = ServletFileUpload.isMultipartContent(request);
	
		if(!isUpload) {
			throw new RuntimeException("当前文件不适合上传");
		}
		
		// (1)创建DiskFileItemFactory工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		
		// 临时文件夹
		// (拓展:如果总是每次请求都写入到硬盘中有不必要的资源浪费,这里可以设置一下给定一个“临时目录”,到达一定的值的时候再一次写入硬盘中)
		factory.setSizeThreshold(1024 * 1024 * 5);// 文件到达5M的时候使用临时文件夹
		
		String realPath2 = this.getServletContext().getRealPath("/tempUpload");// 临时文件夹
		factory.setRepository(new File(realPath2));
		
		// (2)创建核心上传组件
		ServletFileUpload sfUpload = new ServletFileUpload(factory);
		
		// 设置上传文件大小
		// (扩展:可以设置文件上传的大小)
		sfUpload.setFileSizeMax(1024 * 1024 * 3);// 单个文件最大值
		sfUpload.setSizeMax(1024 * 1024 * 10);// 整个最大值
		
		// 因为传递过来的不单单只是一个file请求对象。
		// 所以,对请求的数据进行判断。
		try {
			
			List<FileItem> parseRequest = sfUpload.parseRequest(request);// 获取所有请求数据
			
			for (FileItem fileItem : parseRequest) {
				
				// 判断是否是文件
				if(fileItem.isFormField()) {
					
					// 为普通请求参数
					String fieldName = fileItem.getFieldName();// 请求字段名称
					String value = fileItem.getString("utf-8");// 请求字段值
					System.out.println(fieldName+"、"+value);
					
				}else {// 上传文件
					
					String name = fileItem.getName();// 获取文件名
					
					// 文件重名 使用	uuid
					// (扩展:如果是很多用户提交了文件,可是用户可能会提交的名称是相同的。这样会造成,资源覆盖等问题)
					name = name.substring(name.lastIndexOf("\\") + 1); // 字符串截取再拼接
					name = UUID.randomUUID() + "_" + name;
					
					InputStream inputStream = fileItem.getInputStream();// 获取输入流
					
					String realPath = this.getServletContext().getRealPath("/upload");// 设置保存路径
					
					// 多级目录的设置
					// (扩展:如果总是向一个文件夹里面写内容。总有一天资源会超过这个文件夹的最大容量,所有需要设置多级目录)
					LocalDate now = LocalDate.now();
					int year = now.getYear();
					int month = now.getMonthValue();
					int day = now.getDayOfMonth();
					
					// 使用upload下创建年月日三级子目录
					realPath = realPath + "/" + year + "/" + month + "/" + day;
					
					// 创建父目录
					File file2 = new File(realPath);
					// 如果父目录不存在,就创建子目录
					if(!file2.exists()) {
						file2.mkdirs();
					}
					
					
					File file = new File(realPath,name);// 创建文件对象
					
					FileOutputStream fileOutputStream = new FileOutputStream(file);// 写入realPath路径中
					
					// 转为底层字节形式存入
					byte[] by = new byte[1024];
					int length = -1;
					
					while ((length = inputStream.read(by)) != -1) {
						fileOutputStream.write(by, 0 , length);
					}
					
					// 关闭流
					inputStream.close();
					fileOutputStream.close();
					fileItem.delete();
					
				}
			}
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
Jsp+Servlet的文件上传 index.jsp <%@ page contentType="text/html; charset=GBK"%> <html> <head> <body> <form method="post" action="upload.jsp" name="pw" enctype="multipart/form-data"> 文件一 <input type="file" name="file1"> <br> 文件二 <input type="file" name="file2"> <br> 文件三 <input type="file" name="file3"> <br> <input TYPE="submit" value="确定上传"> </form> </body> </html> upload.jsp <%@ page language="java" import="fileUpload.*"%> <%@ page contentType="text/html;charset=gb2312"%> <%@ page errorPage="error.jsp"%> <%@ page import="java.io.File,java.util.*,java.text.*"%> <!-- 初始化一个upBean--> <jsp:useBean id="myUpload" scope="page" class="fileUpload.upBean" /> <% //初始化工作 myUpload.initialize(pageContext); //设定允许的文件后缀名 //myUpload.setAllowedExtList("gif,jpg"); //设定允许上传的文件类型 //gif:gif //jpg:pjpeg //text:plain //html:html //doc:msword // myUpload.setAllowedFileTypeList("gif,jpg"); //设定是否允许覆盖服务器上的同名文件 myUpload.setIsCover(false); //设定允许上传文件的总大小 //myUpload.setTotalMaxFileSize(1000000); //设定单个文件大小的限制 //myUpload.setMaxFileSize(100000); String myName = new String(""); //设定上传的物理路径 myUpload.setRealPath(application.getRealPath(File.separator + "upload")); try { //将所有数据导入组件的数据结构中 myUpload.upload(); } catch (Exception e) { throw e; } //得到所有上传的文件 files myFiles = myUpload.getFiles(); String[] sourceName = new String[myFiles.getCount()]; //文件的原始文件名数组 //将文件保存到服务器 try { for (int i = 0; i < myFiles.getCount(); i++) { Date date = new Date(); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmsszzz"); String name = System.currentTimeMillis() + ""; // myName="myName"; // myName=myName+"_"+i+"."+myFiles.getFile(i).getExtName(); myName = name + "." + myFiles.getFile(i).getExtName(); //保存的图片名称 sourceName[i] = myFiles.getFile(i).getName(); myFiles.getFile(i).setName(myName); //有两种保存方法,一种是保存在myUpload.setRealPath()的设定路径中,使用saveAs(),一种是另外保存到其他文件夹,使用.saveAs(String realPath) myFiles.getFile(i).saveAs(); Thread.sleep(50); } } catch (Exception e) { throw e; } %> <html> <head> <title>上传结果</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta http-equiv="expires" content="fri,30 dec 1999 00:00:00 gmt"> <meta name="author" content="fredwebs@sina.com"> <link rel='stylesheet' href='style.css' type='text/css'> </head> <body bgcolor="#999999" style="margin: 0;"> 上传成功! </table> </body> </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值