Jsp上传文件

 

在使用这个servlet之前要导入两个jar包:

commons-fileupload-1.4.jar

commons-io-2.8.0.jar

不想找的可以直接点连接下载:

https://download.youkuaiyun.com/download/weixin_41936498/16608739

uploadServlet.java文件:

package com.upload;

import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class upload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//判断文件是普通表单还是带文件的表单
				if (!ServletFileUpload.isMultipartContent(request)) {
					return; //终止方法运行,说明这是一个普通的表单,直接返回
					
				}

				//创建上传的文件保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
				String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
				File uploadFile = new File(uploadPath);
				if (!uploadFile.exists()) { //如果文件不存在则创建文件
					uploadFile.mkdir(); //创建这个目录
				}

				//缓存,临时文件
				//临时路径,假如文件超过了预期的大小,我们就把他放到一个临时文件中,过几天自动删除,或者提醒用户转存为永久
				String tmpPath =  this.getServletContext().getRealPath("/WEB-INF/tmp");
				File tmpFile = new File(tmpPath);
				if (!tmpFile.exists()) {
					tmpFile.mkdir(); //创建这个临时目录
				}
				try {
					
					
					//1. 创建DiskFileItemFactory对象,处理文件上传路径或者大小限制
					DiskFileItemFactory factory = new DiskFileItemFactory();

					factory.setSizeThreshold(1024 * 1024); //缓冲区大小为1M
					factory.setRepository(tmpFile);	//临时目录的保存目录,需要一个
					
					
					//2. 获取ServletFileUpload
					ServletFileUpload upload = new ServletFileUpload(factory);
					//设置乱码
					upload.setHeaderEncoding("UTF-8");
					//设置单个文件最大值 1M
					upload.setFileSizeMax(1024 * 1024 *10);
					//设置总共能够上传文件大小 1M
					upload.setSizeMax(1024 * 1024 *10);
					
					
					//3. 处理上传文件
					String massage = "";
					//把请求解析,封装成一个FileItem对象
					List<FileItem> fileItems = upload.parseRequest(request);
					if (fileItems != null && fileItems.size() > 0) { //判断是否存在文件
						for(FileItem fileItem : fileItems) { 
							
							if (fileItem.isFormField()) {//判断上传的文件是普通的表单还是带文件的表单
								//getFileName 指的是前端表单控件的name
								String name = fileItem.getFieldName();
								String value = fileItem.getString("UTF-8");//处理乱码
								System.out.println(name+":"+value);
							}else { //判断他是上传的文件
								//===================处理文件-==============//
								//拿到文件名字
								String uploadFileName = fileItem.getName();
								System.out.println("上传的文件名:"+uploadFileName);
								
								if(uploadFileName.trim().equals("")||uploadFileName == null) {
									
									continue;
								}
								//获得上传文件名 
								String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") +1);
								
								//获得文件的后缀名
								String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") +1);
															
								//使用UUID(唯一识别通用码),保证文件名唯一;
								//UUID.randomUUID(),随机生成一个唯一识别的通用码
								String uuidPath = UUID.randomUUID().toString();
								
								//=============处理文件完毕================//

								//文件真是存在的路径 realPath
								String realPath = uploadPath+"/"+uuidPath;
								//给每个文件创建一个对应的文件夹
								File realPathFile = new File(realPath);
								if(!realPathFile.exists()) {
									realPathFile.mkdir();
								}
								
								//==========存放地址完毕==============
								
								//获得文件上传的流
								InputStream inputStream = fileItem.getInputStream();
								
								//创建一个文件输出流
								//realPath = 真实的文件夹
								//差了一个文件;加上输出文件的名字+"/"+uuidFileName
								FileOutputStream fos= new FileOutputStream(realPath +"/"+ fileName);
								
								//创建一个缓冲区
								byte buffer[] = new byte[1024*1024];
								
								//判断是否读取完毕
								int len = 0;
								//如果大于0说明还存在数据
								while((len = inputStream.read(buffer))!=-1) {
									fos.write(buffer,0,len);
								}
								
								//关闭流
								fos.close();
								inputStream.close();
								
								massage = "文件上传成功";
								fileItem.delete();//上传成功,清除临时文件
							}
						}
					}
					//servlet请求转发消息
					request.setAttribute("massage", massage);
					request.getRequestDispatcher("/massage.jsp").forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}
			

}

massage.jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	${massage }
</body>
</html>

uploadFile.jsp文件:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" action="${pageContext.request.contextPath }/TomcatTest/UploadServlet" enctype="multipart/form-data" >
    用户名:	
	<input type="text" name="username" />
	<br/><br/>
    选择一个文件:
    <input type="file" name="uploadFile" />
    <br/><br/>
    <input type="submit" value="上传" />
</form>

</body>
</html>

xml核心文件:
 

<servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.upload.upload</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/TomcatTest/UploadServlet</url-pattern>
  </servlet-mapping>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值