简单的文件上传的下载(动态web项目)

时间:2023-10-20 13:57:01

1、在页面中定义一个form表单,如下:

 <!-- 文件上传 -->
<form action="${pageContext.request.contextPath}/FileServlet?oper=fileUpload" method="post"
enctype="multipart/form-data">
用户名:<input type="text" name="username"><br><!--普通表单项,没有用-->
<input type="file" name="file"><br>
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
<!-- 文件下载 -->
<a href="${pageContext.request.contextPath}/RegisterServlet?oper=fileDownload">下载</a>

注意:

向服务器上传一个文件时,表单要使用post请求。
表单的默认属性enctype="application/x-www-form-urlencoded",这个属性的意思是请求体中的内容将会使用URL编码
上传文件的表单enctype需要设置为 multipart/form-data
multipart/form-data表示的是表单是一个多部件的表单
如果类型设置为它,则我们的每一个表单项都会作为一个单独的部件发送给服务器。
多个部件之间使用类似 -----------------------------7df2d08c0892 分割符来分开
当表单设置为multipart/form-data时,我们request.getParameter()将失效,我们不能再通过该方法获取请求参数。

2、在doPost方法中,(需要导入两个jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar)

文件上传和下载的jar包(百度云) 密码:ftbi

 //使用简单的反射将参数oper映射成函数对象
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String methodName = request.getParameter("oper");
Class cla = this.getClass();
try {
Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.setAccessible(true);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);//doPost()中调用doGet()方法
}
protected void fileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 1、创建工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
// 2、创建ServletFileUpload对象,通过这个对象完成文件上传功能
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setFileSizeMax(150*1024);//对单个文件大小做限制
fileUpload.setSizeMax(2*1024*1024);//对总文件大小做限制
ServletContext servletContext = request.getServletContext();//获取servletContext对象
String realPath=servletContext.getRealPath("/upload");//获取服务器的根目录(存储)
File file=new File(realPath);
if(!file.exists()){//如果目录不存在,则创建该目录
file.mkdirs();
}
try {
// 3、用这个fileUpload对象解析request请求
List<FileItem> fileList = fileUpload.parseRequest(request);
for (FileItem item : fileList) {
// 如果是普通表单项
if (item.isFormField()) {
String name = item.getFieldName();// 获取name属性
String value = item.getString("utf8");// 获取value值
// System.out.println(name + ":" + value);
} else {// 如果上传的是文件
// String contentType = item.getContentType();// 获取文件的类型
// String fieldName = item.getFieldName();// 获取文件域的name属性
long size = item.getSize();// 获取文件的大小
if(size==0){//如果没有上传文件,则继续往下执行
continue;
}
String name = item.getName();// 获取文件的名字
//在IE浏览器中获取到的是文件名的全路径,需要通过截取字符串获得文件的名字
//谷歌和火狐中获取的只是文件的名字,不需要截取
if(name.contains("\\")){
name=name.substring(name.lastIndexOf("\\")+1);
}
//为了上传同名文件时不被覆盖,需要对文件的名字进行加前缀处理
String prefix = UUID.randomUUID().toString();//UUID:机器码+时间戳
prefix = prefix.replace("-", "");
String fileName = prefix+"_"+name;
//将文件写到服务器
item.write(new File(realPath+"//"+fileName));
}
}
}catch(FileSizeLimitExceededException e) {
System.out.println("文件大小不能超过150K");
}catch(SizeLimitExceededException e) {
System.out.println("文件总大小不能超过2M");
}catch (FileUploadException e) {
e.printStackTrace();
}
}
protected void fileDownload(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
ServletContext servletContext = request.getServletContext();
String fileName = "海若有因.mp3";
String path = servletContext.getRealPath("/WEB-INF/res/"+fileName);
File file = new File(path);
//1.创建输入流
InputStream in = new FileInputStream(file);
//获取文件的MIME类型
String type = servletContext.getMimeType(path);
//设置响应头---文件类型 Content-Type为文件的MIME类型
response.setContentType(type);
//解决文件名中文乱码的问题
fileName = new String(fileName.getBytes("gbk"),"iso8859-1");//这是一种不太讲理的方式
//设置响应头---下载文件的信息 Content-Disposition为attachment; filename=文件名
//Content-Disposition告诉浏览器如何处理文件
//attachment 告诉浏览器这个文件是一个附件的形式发给你的,需要你做下载的操作
//filename 告诉浏览器下载文件的名字
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//从response获取输出流,不需要手动关闭
ServletOutputStream out=response.getOutputStream();
//将输入流写到输出流
IOUtils.copy(in, out);
in.close();//关闭输入流
}

函数反射参见:用简单的反射优化代码(动态web项目)