当前位置:网站首页>Simple uploading and downloading of Web project files
Simple uploading and downloading of Web project files
2022-07-26 17:58:00 【Supra code heartbeat】
Simple uploading and downloading of files
One 、 Upload files
- need jar package ( You can download it once you search the Internet )

- The front-end code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- It specifies base label -->
<base href="<%=request.getContextPath()+"/"%>>">
<style type="text/css">
input[type="submit"] {
outline: none;
border-radius: 5px;
cursor: pointer;
background-color: #31B0D5;
border: none;
width: 70px;
height: 35px;
font-size: 20px;
}
img {
border-radius: 50%;
}
form {
position: relative;
width: 200px;
height: 200px;
}
input[type="file"] {
position: absolute;
left: 0;
top: 0;
height: 200px;
opacity: 0;
cursor: pointer;
}
</style>
<script type="text/javascript">
function prev(event) {
// Get the area where the picture is displayed
var img = document.getElementById("prevView");
// Get file object
var file = event.files[0];
// Get file reader : Js Of a class , It can be used directly
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
// to img Of src Set pictures url
img.setAttribute("src", this.result);
}
}
</script>
</head>
<body>
<!-- Form enctype Property to be set to multipart/form-data
enctype="multipart/form-data" Indicates that the submitted data is constructed in multiple parts , There are documents and text
-->
<form action="fileUploadServlet" method="post" enctype="multipart/form-data">
chart : <img src="2.jpg" alt="" width="200" height="200" id="prevView">
<input type="file" name="pic" id="" value="" οnchange="prev(this)"/>
name : <input type="text" name="name"><br/>
<input type="submit" value=" Upload "/>
</form>
</body>
</html>
- servlet Code
package mzq.servlet;
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;
import utils.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("FileUploadServlet Called ...");
//1. Determine whether it is a file form (enctype="multipart/form-data")
if (ServletFileUpload.isMultipartContent(request)) {
//System.out.println("OK");
//2. establish DiskFileItemFactory object , It is used to build a tool object for parsing uploaded data
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//3. Create a tool object to parse the uploaded data
ServletFileUpload servletFileUpload =
new ServletFileUpload(diskFileItemFactory);
// Solve the problem that the received file name is Chinese garbled
servletFileUpload.setHeaderEncoding("utf-8");
//4. The key point , servletFileUpload Object can send the data submitted by the form text / file
// Encapsulate it in FileItem In the file item
try {
List<FileItem> list = servletFileUpload.parseRequest(request);
for (FileItem fileItem : list) {
//System.out.println("fileItem=" + fileItem);
// Judge whether it's a file
if (fileItem.isFormField()) {
// If it is true It's text input text
String name = fileItem.getString("utf-8");
} else {
// It's a document
// In one way
// Get the name of the uploaded file
String name = fileItem.getName();
System.out.println(" Uploaded file name =" + name);
// Upload this to Server's temp Save the files in the directory you specified
//1. Specify a directory , It's under the working directory of our website
String filePath = "/upload/";
//2. Get the full directory [io/servlet Basics ]
// This directory is related to your web Bound to the project running environment . It's dynamic .
String fileRealPath =
request.getServletContext().getRealPath(filePath);
//3. Create this uploaded Directory => Create directory ?=> Java Basics
// Teacher thinking ; We also have a tool class , Can return /2024/11/11 character string
File fileRealPathDirectory = new File(fileRealPath + WebUtils.getYearMonthDay());
if (!fileRealPathDirectory.exists()) {
// non-existent , create
fileRealPathDirectory.mkdirs();// establish
}
//4. Copy the file to fileRealPathDirectory Catalog
// Build a complete path for uploading files : Catalog + file name
// Process the uploaded file name , Add a prefix before , Guarantee is the only thing , Pretty good
name = UUID.randomUUID().toString() + "_" + name;
String fileFullPath = fileRealPathDirectory + "/" +name;
fileItem.write(new File(fileFullPath));
//5. Prompt information
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(" Upload successful ~");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println(" Not a file form ...");
}
}
private void saveFile(){
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
- WebUtils
import java.time.LocalDateTime;
public class WebUtils {
public static String getYearMonthDay() {
// How to get the current date -> java Basics date Third generation class
LocalDateTime ldt = LocalDateTime.now();
int year = ldt.getYear();
int monthValue = ldt.getMonthValue();
int dayOfMonth = ldt.getDayOfMonth();
String yearMonthDay = year + "/" + monthValue + "/" + dayOfMonth + "/";
return yearMonthDay;
}
}
Be careful :
Upload files , establish web/upload Folder , stay tomcat Startup time , Not in the out Under the table of contents establish Yes Ought to be upload Folder , as a result of tomcat The corresponding empty directory will not be in out Create the corresponding directory under , therefore , only Need to be in upload Under the table of contents , Just put a file , This is Idea + Tomcat The problem of , Actual development will not exist
Two 、 File download
- Front end simple code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> File download </title>
<base href="<%=request.getContextPath()+"/"%>>">
</head>
<body>
<h1> File download </h1>
<a href="fileDownLoadServlet?name=1.jpg"> Click download picture </a><br/><br/>
<%--1.jpg For the file name you want to download on the server The location of the server here is download Next --%>
</body>
</html>
- FileDownloadServlet
package mzq.servlet;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
public class FileDownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. First prepare the file to be downloaded [ Assume that these files are public resources ]
// important : Promise to be our tomcat After starting , In the working directory out There are download Folder , There are files available for download !!
// If you don't see what you created download In the working directory out Next rebuild project -> restart, Just OK
//2. Get the name of the file to download
request.setCharacterEncoding("utf-8");
String downLoadFileName = request.getParameter("name");
//System.out.println("downLoadFileName= " + downLoadFileName);
//3. to http Respond to , Set the response header Content-Type , It's a document MIME
// adopt servletContext To get
ServletContext servletContext = request.getServletContext();
String downLoadPath = "/download/"; // Download directory from web Project root directory calculation /download/1.jpg
String downLoadFileFullPath = downLoadPath + downLoadFileName;
String mimeType = servletContext.getMimeType(downLoadFileFullPath);
System.out.println("mimeType= " + mimeType);
response.setContentType(mimeType);
//4. to http Respond to , Set the response header Content-Disposition
// There are many details to consider here , For example, different browsers write differently , Consider coding
// ff yes The file name in Chinese needs base64, and ie/chrome yes URL code
// Here we only need to know the principle
//(1) If it is Firefox The Chinese code needs base64
//(2)Content-Disposition Is the display form of the specified downloaded data , If attachment Then use the file download method
//(3) If it's something else ( Main stream ie/chrome) Chinese code use URL code
if (request.getHeader("User-Agent").contains("Firefox")) {
// firefox Base64 code
response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" +
new BASE64Encoder().encode(downLoadFileName.getBytes("UTF-8")) + "?=");
} else {
// other ( Main stream ie/chrome) Use URL Coding operation
response.setHeader("Content-Disposition", "attachment; filename=" +
URLEncoder.encode(downLoadFileName, "UTF-8"));
}
//5. Read the downloaded file data , Return to the client / browser
//(1) Create a file to download , Associated input stream
InputStream resourceAsStream =
servletContext.getResourceAsStream(downLoadFileFullPath);
//(2) Get the output stream of the returned data [ Because most of the returned files are binary ( byte ), IO java Basics ]
ServletOutputStream outputStream = response.getOutputStream();
//(3) Use tool class , The file associated with the input stream , Copy to the output stream , And return it to the client / browser
IOUtils.copy(resourceAsStream, outputStream);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
边栏推荐
- Ascend target detection and recognition - customize your own AI application
- 4、 Service communication principle, code implementation
- (25) top level menu of blender source code analysis blender menu
- Asemi rectifier bridge kbpc2510, kbpc2510 parameters, kbpc2510 specifications
- 【集训Day3】section
- [Day2] cinema ticket
- Week 17 free intrusion pointer exercise - output maximum
- Definition of graph traversal and depth first search and breadth first search (I)
- 国际大咖 VS 本土开源新星 | ApacheCon Asia 主题演讲议程全览
- 2.1.2 synchronization always fails
猜你喜欢

天翼云Web应用防火墙(边缘云版)支持检测和拦截Apache Spark shell命令注入漏洞

2022年的PMP考试大纲是什么?

树形dp问题

AI zhetianchuan DL regression and classification

Performance tuning bugs emerge in endlessly? These three documents can easily handle JVM tuning

【云原生】 iVX 低代码开发 引入腾讯地图并在线预览

RedisDesktopManager去除升级提示

COSCon'22城市/学校/机构出品人征集令

国际大咖 VS 本土开源新星 | ApacheCon Asia 主题演讲议程全览

【集训Day2】Sculpture
随机推荐
[training Day2] torchbearer
AI sky covering DL multilayer perceptron
树形dp问题
就这一次!详细聊聊分布式系统的那些技术方案
AI遮天传 DL-回归与分类
JS recursive Fibonacci sequence deep cloning
uni-app
3、 Topic communication: create your own information format
[training Day1] Dwaves line up
PMP考试详解,新考纲有什么变化?
常用api
二层管理型交换机如何设置IP
老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破
Ascend目标检测与识别-定制自己的AI应用
Ascend target detection and recognition - customize your own AI application
【数字IC】深入浅出理解AXI-Lite协议
Heavy! The 2022 China open source development blue book was officially released
如何通过学会提问,成为更加优秀的数据科学家
国际象棋机器人夹断7岁男孩手指,原因是「棋手违反安全规则」?
性能调优bug层出不穷?这3份文档轻松搞定JVM调优