当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢

The user experience center of Analysys Qianfan bank was established to help upgrade the user experience of the banking industry

重磅!《2022中国开源发展蓝皮书》正式发布

【集训Day2】Torchbearer

Cross site scripting attack (XSS)

Spark unified memory partition

AI sky covering DL multilayer perceptron

CCS tm4c123 new project

Week 17 free intrusion pointer exercise - output maximum

Heavy! The 2022 China open source development blue book was officially released

5、 Parameter server principle, code implementation
随机推荐
Machine learning by Li Hongyi 2. Regression
Week 17 free intrusion pointer exercise - output maximum
9、 Alternative implementation of client for service communication
Is it safe for Changzheng securities to open an account?
天翼云Web应用防火墙(边缘云版)支持检测和拦截Apache Spark shell命令注入漏洞
相对路径与绝对路径
Interview with celebrities | open source is a double-edged sword for security -- Wei Jianfan, author of the Chinese translation of cathedral and market
URL跳转漏洞
点击劫持攻击
ACL实验演示(Huawei路由器设备配置)
OpenWrt之feeds.conf.default详解
1、 C language program structure, compilation and operation, data type related
【集训Day1】 Dwarves line up
Analysis of interface testing
跨站点请求伪造(CSRF)
【云原生】 iVX 低代码开发 引入腾讯地图并在线预览
Linux安装mysql8.0.29详细教程
PIP installation module, error
Coscon'22 city / school / institution producer solicitation order
VS Code 格式化后 自动让函数名后有空格