Java 文件上传下载
html
<body>
<form action="${pageContext.request.contextPath}/user/upload" enctype="multipart/form-data"
method="post"><%--get方法传数据有大小限制,post方法不会限制--%>
姓名:<input type="text" name="username" placeholder="请输入姓名"/>
头像:<input type="file" name="headImage"/>
<input type="submit" value="上传">
</form>
<a href="${pageContext.request.contextPath}/user/download?image=2.jpg"><img src="images/2.jpg"></a><br>
</body>
上传
@WebServlet("/user/upload")
public class UpLoadFileServlet extends javax.servlet.http.HttpServlet {
private UserService us = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 判断请求是否是文件上传请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
// 表名当前的请求不是一个文件上传的请求。
return;// 程序结束
}
// 构造一个user对象
User user = new User();
try {
// 2. Create a factory for disk-based file items 创建FileItem工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// this 指代 当前Servlet对象
// 3. Create a new file upload handler 创建一个文件上传处理器 核心对象
ServletFileUpload upload = new ServletFileUpload(factory);
// 3.2 设置文件上传的大小 单个文件的大小 文件上传总和值
// 单位:字节 byte
upload.setFileSizeMax(1024 * 1024 * 5);// 5MB
upload.setSizeMax(1024 * 1024 * 100); // 100MB
// 文件上传 transferTo()
// 4. Parse the request 解析客户端发送的请求 装配的是提交的一个个表单项
List<FileItem> items = upload.parseRequest(request);
// 5. 遍历表单项集合 进行循环判断
for (FileItem item : items) {
// 判断某一个表单项是不是一个文件上传的表单项
if (item.isFormField()) { // 是一个普通的表单项
//String fieldName = item.getFieldName();//--->表单项名称
String name = item.getFieldName();// 获取的是name属性名称
// 设置普通表单项的编码字符集
String value = item.getString("utf-8"); // 获取的是name属性名称对应的值
System.out.println(name + "------" + value);// username ------ 张三
// 把用户名的信息也放进到user对象中
user.setU_name(value);
} else {
// 不是一个普通的表单项
String fileName = item.getName();// 获取的是表单项的对应的值 文件名称
String path = "D:\\upload";// 上传文件的目标地址
// 文件的名称需要做单独处理 防止文件上传过程中文件重名覆盖现象
// 使用Java中提供的工具类 UUID
String headName = UUID.randomUUID().toString().replaceAll("-", "");
//long timeMillis = System.currentTimeMillis();
// 获取文件的字节输入流 流中包含上传文件的数据
InputStream is = item.getInputStream();
fileName = headName + fileName;
// 文件字节输出流
File destFile = new File(path);
if (!destFile.exists() && !destFile.isDirectory()) {
destFile.mkdirs();// 多级目录创建
}
// 真实的路径
//String realPath = path + "\\" + fileName;// 拼接路径
String realPath = "http://localhost:8080\\upload\\" + fileName;// 映射磁盘中的“D:\\upload”
// 将来需要把路径存储到数据库中
user.setPic_path(realPath);
// 真正上传的文件 指向"D:\\upload目录下
File file = new File(destFile, fileName);
FileOutputStream os = new FileOutputStream(file);
// 一读一写
int len = 0;
byte[] buff = new byte[1024];
while ((len = is.read(buff)) != -1) {
os.write(buff,0,len);
}
// 释放流对象
os.close();
is.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// 关联service层 通过用户名添加到对应的记录中
boolean flag = us.addUserPic(user);
if (flag) {
// 添加到表中成功
request.setAttribute("user", user);
request.getRequestDispatcher("/showMessage.jsp").forward(request, response);
} else {
// 没有上传成功 再来一次
request.getRequestDispatcher("/upload.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
下载
@WebServlet("/user/download")
public class DownloadFileServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
String image = request.getParameter("image");
// 浏览器的编码字符集 latin iso-8859-1
//byte[] bytes = image.getBytes("ISO8859-1");
// image = new String(bytes, "UTF-8");
image = new String(image.getBytes("ISO-8859-1"),"UTF-8");
// 服务器告诉浏览器客户端以附件的形式打开
// 设置响应头 content-disposition 值为 attachment 附件
System.out.println(image);
response.setHeader("content-disposition","attachment;filename="+image);// 手动指定下载的文件名称
// 下载 还是以流的形式进行copy
String realPath = this.getServletContext().getRealPath("/images");
// 设置响应的mime类型
response.setContentType(this.getServletContext().getMimeType(image));// jpg --> image/jpeg
// 就是image的路径
File file = new File(realPath, image);
// 放进字节输入流中
FileInputStream fis = new FileInputStream(file);
// 获取字节输入流
ServletOutputStream os = response.getOutputStream();
// 一读一写
int len = 0;
byte[] buff = new byte[1024];
while ((len = fis.read(buff)) != -1) {
os.write(buff,0,len);
}
// 释放流资源
os.close();
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
所需Jar包