1.创建web项目
2. 上传文件页面
必须要设置input输入项的name属性,否则浏览器将不会发送上传文件的数据
必须把form的enctype属值设为multipart/form-data.设置该值后,浏览器在上传文件时,将把文件数据附带在http请求消息体中,
并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
3.
使用Commons-fileupload组件实现文件上传,需要导入该组件相应的支撑jar包:Commons-fileupload和commons-io。
将jar包放置lib文件夹下后,还需配置他的位置信息
4.上传文件Servlet
DiskFileItemFactory 是创建 FileItem 对象的工厂
ServletFileUpload 负责处理上传的文件数据,并将表单中每个输入项封装成一个 FileItem 对象中
FileItem类负责处理表单提交的字段
上传文件步骤:
package com.study;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得一个文件上传的工厂类
DiskFileItemFactory dfif = new DiskFileItemFactory();//DiskFileItemFactory 是创建 FileItem 对象的工厂
//设置文件上传临时存储的大小8M
dfif.setSizeThreshold(1024*1024*8);
//指定临时文件目录,默认值为当前用户的系统临时文件目录,可通过System.getProperty(“java.io.tmpdir”)打印查看;
dfif.setRepository(new File("java.io.tmpdir"));
System.out.println(System.getProperty("java.io.tmpdir"));
//使用servlet来处理文件上传
ServletFileUpload upload = new ServletFileUpload(dfif);
//设置文件上传的大小
upload.setSizeMax(1024*1024*50);
//获得当前服务器的路径
String uploadPath = this.getServletContext().getRealPath("");
System.out.println("当前服务器路径---->"+uploadPath);
uploadPath = uploadPath+"..\\"+"upload";
File uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
}
try {
List formItem = upload.parseRequest(request);
if(formItem != null && formItem.size() >0){
//循环遍历要上传的文件
for(FileItem item : formItem){
if(!item.isFormField()){
//获得要上传的文件的名字
String fileName = new File(item.getName()).getName();
//fileName = new Date().getTime()+(int)(Math.random()*100)+fileName;
//目的文件
String filePath = uploadPath+"\\"+fileName;
File storeFile = new File(filePath);
item.write(storeFile);
System.out.println(fileName);
System.out.println(filePath);
//request.setAttribute("fileName", fileName);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("message", "文件上传失败:"+e.getMessage());
request.getRequestDispatcher("error.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("upload.jsp").forward(request, response);
}
}
5.下载文件页面
下载
6.下载文件Servlet
服务器希望浏览器不直接处理相应的实体内容,而是由用户选择将相应的实体内容保存到一个文件
这需要设置 Content-Disposition 响应头。
先使用文件输入流 将文件读到内存中 再使用输出流 将文件输出给用户
package com.study;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DownLoadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//实现文件下载 设置响应头
String fileName = this.getServletContext().getRealPath("")+"../"+"upload/"+"zly.jpg";
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
System .out.print("fileName"+fileName);
//先使用文件输入流 将文件读到内存中 再使用输出流 将文件输出给用户
File file = new File(fileName);
FileInputStream fileIn = new FileInputStream(file);
//准备一个缓冲区
byte[] b = new byte[(int)file.length()];
//将文件读入缓冲区中
fileIn.read(b);
//获得响应的输出流
ServletOutputStream sout = response.getOutputStream();
//调用response.getOutputStream()方法返回 ServeltOutputStream 对象来向客户端写入文件内容。
sout.write(b);
sout.close();
}
}