松鼠的博客

导航

JavaWeb--文件上传和下载

上传文件
如何实现文件上传
要实现Web开发中的文件上传功能,通常只需完成两步操作
1、在Web界面中添加上传输入项
2、在Servlet中读取上文件的表单页面,并保存到硬盘中

文件上传的相关API
Filetem接口
它只要用于Commons-FileUpload组件当中,主要是封装单个表单字段元素。

DiskFiletemFactory类
它可以用于将请求消息实体中的每一个文件封装成单独的对象。

ServletFileUpload类
它是Apache组件处理文件上传的核心高级类,它可以将表单中的数据封装成一个对象

实战-实现文件上传
程序实现
上传界面html

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<table width="600px">
<tr>
<td>上传者</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>上传文件</td>
<td><input type="file" name="myfile" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="上传" /></td>
</tr>
</table>
</form>
</body>
</html>

创建Servlet

package cn.itcast.fileupload;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//上传文件的Servlet类
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//设置ContentType字段值
response.setContentType("text/html;charset=utf-8");
// 创建DiskFileItemFactory工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置文件缓存目录,如果该目录不存在则新创建一个
File f = new File("E:\\TempFolder");
if (!f.exists()) {
f.mkdirs();
}

factory.setRepository(f);

ServletFileUpload fileupload = new ServletFileUpload(factory);

fileupload.setHeaderEncoding("utf-8");
// 解析 request,得到上传文件的FileItem对象
List<FileItem> fileitems = fileupload.parseRequest(request);
//获取字符流
PrintWriter writer = response.getWriter();
// 遍历集合
for (FileItem fileitem : fileitems) {
// 判断是否为普通字段
if (fileitem.isFormField()) {
// 获得字段名和字段值
String name = fileitem.getFieldName();
if(name.equals("name")){
//如果文件不为空,将其保存在value中
if(!fileitem.getString().equals("")){
String value = fileitem.getString("utf-8");
writer.print("上传者:" + value + "<br>");
}
}
} else {

String filename = fileitem.getName();

if(filename != null && !filename.equals("")){
writer.print("上传的文件名称是:" + filename + "<br>");

filename = filename.substring(filename.lastIndexOf("\\") + 1);
// 文件名需要唯一
filename = UUID.randomUUID().toString() + "_" + filename;

String webPath = "/upload/";

String filepath = getServletContext().getRealPath(webPath + filename);
// 创建文件
File file = new File(filepath);
file.getParentFile().mkdirs();
file.createNewFile();

InputStream in = fileitem.getInputStream();

FileOutputStream out = new FileOutputStream(file);

byte[] buffer = new byte[1024];//每次读取1个字节
int len;

while ((len = in.read(buffer)) > 0)
out.write(buffer, 0, len);

in.close();
out.close();

fileitem.delete();
writer.print("上传文件成功!<br>");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

 

实战-下载文件

下载界面html

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.net.URLEncoder"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下载</title>
</head>
<body>
<%-- <a href="/chapter12/DownloadServlet?filename=<%=URLEncoder.encode("VS.png", "utf-8")%>">文件下载 </a>--%>
<a href="/chapter12_war_exploded/DownloadServlet?filename=VS.png">文件下载</a>
<%--<a href="download/VS.png">文件瞎子</a>--%>
</body>
</html>

创建Servlet

package cn.itcast.fileupload;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//上传文件的Servlet类
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//设置ContentType字段值
response.setContentType("text/html;charset=utf-8");
// 创建DiskFileItemFactory工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置文件缓存目录,如果该目录不存在则新创建一个
File f = new File("E:\\TempFolder");
if (!f.exists()) {
f.mkdirs();
}

factory.setRepository(f);

ServletFileUpload fileupload = new ServletFileUpload(factory);

fileupload.setHeaderEncoding("utf-8");
// 解析 request,得到上传文件的FileItem对象
List<FileItem> fileitems = fileupload.parseRequest(request);
//获取字符流
PrintWriter writer = response.getWriter();
// 遍历集合
for (FileItem fileitem : fileitems) {
// 判断是否为普通字段
if (fileitem.isFormField()) {
// 获得字段名和字段值
String name = fileitem.getFieldName();
if(name.equals("name")){
//如果文件不为空,将其保存在value中
if(!fileitem.getString().equals("")){
String value = fileitem.getString("utf-8");
writer.print("上传者:" + value + "<br>");
}
}
} else {

String filename = fileitem.getName();

if(filename != null && !filename.equals("")){
writer.print("上传的文件名称是:" + filename + "<br>");

filename = filename.substring(filename.lastIndexOf("\\") + 1);
// 文件名需要唯一
filename = UUID.randomUUID().toString() + "_" + filename;

String webPath = "/upload/";

String filepath = getServletContext().getRealPath(webPath + filename);
// 创建文件
File file = new File(filepath);
file.getParentFile().mkdirs();
file.createNewFile();

InputStream in = fileitem.getInputStream();

FileOutputStream out = new FileOutputStream(file);

byte[] buffer = new byte[1024];//每次读取1个字节
int len;

while ((len = in.read(buffer)) > 0)
out.write(buffer, 0, len);

in.close();
out.close();

fileitem.delete();
writer.print("上传文件成功!<br>");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

 

参考文章:http://blog.ncmem.com/wordpress/2023/09/27/javaweb-%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论

 

 

posted on 2023-09-27 17:43  Xproer-松鼠  阅读(64)  评论(0编辑  收藏  举报