JavaWeb 实现文件上传下载(笔记)

这篇博客详细记录了在JavaWeb环境中实现文件上传和下载过程中遇到的挑战,包括UpdateServlet和DownLoadServlet的使用,以及如何引入Apache Commons IO和FileUpload库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

只能说全是坑…………


UpdateServlet.java

public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1939130975393034262L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			File f = new File("D:\\Temp");
			if (f.exists()) {
				f.mkdir();
			}
			factory.setRepository(f);
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			fileUpload.setHeaderEncoding("utf-8");
			List<FileItem> filList = fileUpload.parseRequest(request);
			PrintWriter writer = response.getWriter();
			for (FileItem item : filList) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					if (name.equals("name")) {
						if (!item.getString().equals("")) {
							String value = item.getString("utf-8");
							writer.print("上传者" + value + "<br/>");
						}
					}
				} else {
					String filename = item.getName();
					if (filename != null && !filename.equals("")) {
						writer.print("上传的文件名称是:" + filename + "<br/>");
						filename = filename.substring(filename
								.lastIndexOf("\\") + 1);
						filename = filename.replace(" ", "_");
						filename = UUID.randomUUID().toString() + "_blog635_"
								+ filename;
						String webpath = "/upload/";
						String filepath = getServletContext().getRealPath(
								webpath + filename);
						File file = new File(filepath);
						file.getParentFile().mkdir();
						file.createNewFile();
						InputStream in = item.getInputStream();
						FileOutputStream out = new FileOutputStream(file);
						byte[] buffer = new byte[1024];
						int len;
						while ((len = in.read(buffer)) > 0)
							out.write(buffer, 0, len);
						in.close();
						out.close();
						item.delete();
						writer.print("上传文件成功!<br/>");
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}
}

DownLoadServlet.java


public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = -6443548568234690815L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String x = request.getParameter("x");
		String y = request.getParameter("y");
		String aaa = "blog635";
		String xz = x + "_" + aaa + "_" + y;
		xz = new String(xz.getBytes("ISO8859-1"), "utf-8");
		// 通知浏览器以下载方式打开
		response.addHeader("Content-Type", "applicaion/octet-stream");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + xz.substring(45));
		// 通过文件流读取文件
		InputStream in = getServletContext().getResourceAsStream(
				"/upload/" + xz);
		// 获取response对象的输出流
		OutputStream out = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		in.close();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<style type="text/css">
.layout {
	width: 80%;
	height: auto;
	margin: 0 auto;
}

.layout>div {
	height: 80%;
	float: left;
	margin: 10px;
}

.layout>div p {
	width: 90px;
	display: inline-block;
}
</style>
</head>

<body>
	<div class="layout">
		<div>
			<form action="UpdateServlet" method="POST"
				enctype="multipart/form-data">
				<p>上传者</p>
				<input type="text" name="name" /><br />
				<p>上传文件</p>
				<input type="file" name="myfile" /><br /> <input type="submit"
					value="上传" />
			</form>
		</div>
		<div>
			<%
				String path1 = request.getRealPath("/upload/");
				File dir = new File(path1);
				File file[] = dir.listFiles();
				for (int i = 0; i < file.length; i++) {
					File fs = file[i];
					if (fs.isDirectory()) {
						out.println(fs.getName() + " [目录]<br />");
					} else {
						out.println("<li>" + "<a href=" + "DownLoad?x="
								+ fs.getName().substring(0, 36) + "&y="
								+ fs.getName().substring(45) + ">"
								+ fs.getName().substring(45) + "</a></li>"
								+ "<br />");
					}
				}
			%>
		</div>
	</div>
</body>
</html>

<input type="file" name="myfile" multiple/>   // 可实现多文件上传

commons-io-2.6下载地址: https://mirrors.tuna.tsinghua.edu.cn/apache//commons/io/binaries/commons-io-2.6-bin.zip


commons-fileupload-1.3.3-bin下载地址:http://mirrors.hust.edu.cn/apache//commons/fileupload/binaries/commons-fileupload-1.3.3-bin.zip


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值