Java Web应用设计中文件上传和下载功能的实现方法
在Java Web应用程序设计过程中很多场景需要实现文件的上传和下载功能,如考试系统用户注册时要求上传个人照片和下载合格证书、电子邮件中添加附件和下载附件、办公系统中各种格式文件的上传和下载等。文件上传就是通过客户端程序(App、浏览器等)把客户端的各类文件通过网络传输到远端服务器并存储在服务器的外部存储器上的过程,而文件下载则是相反的过程,即客户端用户通过App、浏览器等应用程序把存储在远程服务器上的文件通过网络连接传输到客户端设备并存储在客户端设备外部存储器上的过程。一般来说通过Web应用程序完成上传和下载的文件需要进行大小限制,避免出现响应时间过长,无法完成文件处理的现象,这个可以根据应用程序的不同应用场景来进行限制。对于大型文件的上传和下载功能的实现应该通过专用软件完成,比如cuteFTP、ServU等文件服务器软件。例子程序包括文件上传页面、文件上传Servlet、文件下载Servlet等。
1.文件上传页面(fileUpload.jsp)
该页面程序中涉及到的CSS样式设置可以参考https://www.cnblogs.com/Freeland98/p/17246233.html文件中的方法来设置。
<%@page contentType="text/html;charset=gbk" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP文件上传界面--FileUpload</title>
<link rel="stylesheet" type="text/css" href="css/file.css">
<script type="text/javascript">
var fileTypes = ["image/jpg", "image/jpeg", "image/png", "image/gif"];
function validFileType(vFile) {
return fileTypes.includes(vFile.type);
}
function imageUpdate() {
var fileUpload = document.getElementById("fileUpload");
var preview = document.querySelector(".preview");
while (preview.firstChild) {
preview.removeChild(preview.firstChild);
}
var tempElement = document.createElement("p");
var curFile = fileUpload.files[0];
tempElement.textContent = "文件名称:" + curFile.name + " 文件大小:" + curFile.size + " 字节";
if (curFile) {
if (validFileType(curFile)) {
var image = document.createElement("img");
image.height = 400;
image.src = URL.createObjectURL(curFile);
preview.appendChild(image);
preview.appendChild(tempElement);
} else {
preview.appendChild(tempElement);
}
} else {
tempElement.textContent = "还没有选择上传文件!";
preview.appendChild(tempElement);
}
}
function initForm() {
var fileUpload = document.getElementById("fileUpload");
fileUpload.addEventListener("change", imageUpdate);
return true;
}
</script>
</head>
<body>
<table>
<form id="fileForm" name="fileForm" action="/Jisuanji4/FileUpload" method="post" enctype="multipart/form-data">
<tr><th>文件上传界面</th></tr>
<tr>
<td>
<label for="fileUpload" class="labelButton">选择上传文件</label>
<input id="fileUpload" name="fileUpload" type="file" hidden="true">
</td>
</tr>
<tr><td class="preview"><p>图片文件预览位置</p></td></tr>
<tr>
<td>
<input class="labelButton" id="submit" name="submit" type="submit" value="上传">
<input class="labelButton" id="reset" name="reset" type="reset" value="重置">
</td>
</tr>
</form>
</table>
<script>
initForm();
</script>
</body>
</html>
2.文件上传Servlet(FileUpload.java)
package cn.hbqgy.tools;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
//@WebServlet(name = "FileUpload", urlPatterns = {"/FileUpload"})
public class FileUpload extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>文件上传处理程序</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>文件上传成功!</h1><br>");
String uploadPath = "d://temp";
File uploadFile = new File(uploadPath);
//如果存放上传文件的目录不存在则创建它。
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
//必须将request转换成RequestContext类型的。
RequestContext reqContext = new ServletRequestContext(request);
// 得到所有上传文件
List<FileItem> items = upload.parseRequest(reqContext);
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File upFile = new File(fi.getName());
File savedFile = new File(uploadPath, upFile.getName());
fi.write(savedFile);
out.println("点击链接下载文件:");
out.println("<a href='/Jisuanji4/doDownload?name="
+ fileName + "'>"
+ fileName + "</a><br>");
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
out.println("</body>");
out.println("</html>");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
3.文件下载Servlet(FileDownload.java)
package cn.hbqgy.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownload extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String aFileName = request.getParameter("name");
OutputStream out = response.getOutputStream();
response.setContentType("application/x-msdownload;");
//Content-disposition 是 MIME 协议的扩展,
//MIME 协议指示 MIME 用户代理如何显示附加的文件,该响应头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者网页的一部分),还是以附件的形式下载并保存到本地。
//当 Internet Explorer 接收到头时,它会激活文件下载对话框,
//它的文件名框自动填充了头中指定的文件名。
//服务端向客户端游览器发送文件时,
//如果是浏览器支持的文件类型,
//一般会默认使用浏览器打开,比如txt、jpg等,会直接在浏览器中显示,
//如果需要提示用户保存,就要利用Content-Disposition进行一下处理,
//关键在于一定要加上attachment:
//attachment:表示以附件方式下载,如果要在页面中打开,可以改为inline。
//传递的文件名参数要进行编码转换,否则在客户端提示保存文件时文件名会乱码显示。
response.setHeader("Content-disposition", "attachment; filename="+ new String(aFileName.getBytes("utf-8"), "8859_1"));
File fileLoad = new File("d://temp//", aFileName);
FileInputStream in = null; // 输入流
//定义文件输出缓冲区
byte b[] = new byte[1024];
try {
in = new FileInputStream(fileLoad);
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
} catch (Throwable e) {
System.out.println(e.toString());
} finally {
if(in!=null) in.close();
if(out!=null) out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
4.web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>FileUpload</servlet-name>
<servlet-class>cn.hbqgy.tools.FileUpload</servlet-class>
</servlet>
<servlet>
<servlet-name>FileDownload</servlet-name>
<servlet-class>cn.hbqgy.tools.FileDownload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUpload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FileDownload</servlet-name>
<url-pattern>/FileDownload</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
本文来自博客园,作者:Freeland98,转载请注明原文链接:https://www.cnblogs.com/Freeland98/p/17348754.html
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出,原文链接