当前位置:网站首页>JDBC tool class jdbcfiledateutil uploads files and date format conversion, including the latest, simplest and easiest way to upload single files and multiple files
JDBC tool class jdbcfiledateutil uploads files and date format conversion, including the latest, simplest and easiest way to upload single files and multiple files
2022-04-23 20:14:00 【Jiugui wine!!!】
This document introduces the processing method of file upload , Including current end form The coding type of the form is enctype="multipart/form-data" How to deal with ? And the old way to get the name of the uploaded file , The new method uses a function to get the name of the uploaded file . Finally, it explains the difference and code between uploading one file and uploading multiple files .
One 、 File upload considerations
Current end form The form contains the file upload , Have the following knowledge points :
1.form The data coding type in the form should be written enctype="multipart/form-data" To upload files , This encoding type will upload data in binary form .
2. The problem is coming. , When the encoding type is multipart/form-data when , Backstage through request.getParameter(NAME) Will not be able to get the value of text type .
Two 、 Realize file upload and solve the problem that the value cannot be obtained in the background
The core :servlet3.0 Of Part Interface
adopt @MultipartConfig annotation and HttpServletRequest Of Two new methods getPart() and getParts() Mutual assistance To reach the current end form Form use enctype="multipart/form-data" The function of uploading file and text data .
1. Use @MultipartConfig Annotation can not only make the back-end request.getParameter(NAME) Can get the value of text data , You can also use servlet3 Newly added part Interface , There are two new methods in this interface, which can directly obtain the file data and write it to the save path . So it's very convenient and concise .
2.HttpServletRequest Two new methods getPart() and getParts() To receive the front end form File data transmitted from the form ,getPart() Only one file can be received ,getParts() Can receive multiple files .
3、 ... and 、@MultipartConfig Annotation has four attribute values to specify some attributes of the file .
fileSizeThreshold: Integer value setting , The default value is 0, If the size of the uploaded file exceeds this value , Will first write to the cache file .
location: Save path to upload file .
maxFileSize: Limit file upload size . The default value is -1L, It means unlimited size .
maxRequestSize: Limit multipart/form-data Request format , The default value is -1L, Indicates that there is no limit on the number of .
Point four 、 The whole source code of the old method of file upload
package com.jdbc.utils;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
/* The date data of the form is converted to sql Date format dataTrans(String sr0)
1、 Convert the date in string format of the form to java Date format for
2、 take java The date format of is converted to sql Date format for
Save the uploaded image to the specified storage path savaFile()
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.imageio.IIOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class JdbcFileDateUtil {
public static java.sql.Date dataTrans(String sr0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// Construct the object according to the string pattern specified by the parameter . Realize the relevant conversion between date type and string
java.util.Date sr1 =new java.util.Date();
try {
sr1=sdf.parse(sr0);// Is used to String Type conversion to Date type
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new java.sql.Date((sr1.getTime()));//getTime Gets the distance of the current object 1970 year 1 month 1 Japan 0 when 0 branch 0 Milliseconds in seconds
}
// Save the file selected for form upload to the upload file path specified by the server
// It is applicable to both cases whether there are uploaded files or not
public static String savaFile(String MyFile,HttpServletRequest request) throws ServletException,SQLException, IOException {
String savaPath = "D:\\Web Back end development technology \\uploadFile";
Part part =request.getPart(MyFile);//MyFile The value is html in input Labeled name value
String header=part.getHeader("Content-Disposition");
int start=header.lastIndexOf("=");
filename=header.substring(start+1);
if (filename.length()>2) {
filename=filename.substring(filename.lastIndexOf('\\')+1);
filename=filename.substring(0,filename.length()-1);// Remove the last quotation mark ”
String temp= new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new java.util.Date().getTime());// Time stamp , Add before file name , Used to prevent duplicate file names
filename=temp+"."+filename;
part.write(savaPath+"\\"+filename);// Upload the file and write the path to save
}
return filename;
}
}
Optimize the code : Take out the file name processing process separately and modularize it into a method getFileName(Part part).
( One ) How to upload a file : Use getPart(name)
public static String savaFile(String MyFile,HttpServletRequest request) throws ServletException,SQLException, IOException {
String savaPath = "D:\\Web Back end development technology \\uploadFile";
Part part = request.getPart("MyFile");
String filename = getFileName(part);
part.write(savaPath+"\\"+filename);write() Method . You can directly write the uploaded file to disk
return filename; // To return , Used to store in the database
}
public static String getFileName(Part part) {
String header = part.getHeader("Content-Disposition");
int start=header.lastIndexOf("=");
filename=header.substring(start+1);
if (filename.length()>2) {
filename=filename.substring(filename.lastIndexOf('\\')+1);
filename=filename.substring(0,filename.length()-1);// Remove the last quotation mark ”
String temp= new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new java.util.Date().getTime());// Time stamp , Add before file name , Used to prevent duplicate file names
filename=temp+"."+filename;
return filename;
}
return filename;// If the uploaded file is empty , Then the file name is empty
}
( Two ) How to upload multiple files : Use getParts()
public static String savaFiles(String MyFile,HttpServletRequest request) throws ServletException,SQLException, IOException {
String savaPath = "D:\\Web Back end development technology \\uploadFile";
// From the front end form Get all file data in and store it in a list in
List<Part> parts = (List<Part>) request.getParts();
// Loop through the file , Each loop gets the name of a file and writes the file data to disk
// Get current part Point to the input Labeled name, Only name In order to MyFile Can enter the operation of getting file name only if it starts with the value of ,
// Or jump to the next part, there part.getName().startsWith(MyFile) The key point is to understand and combine the front-end input Of name Value understanding
// startsWith() The parameter of is the corresponding to the upload folder input Labeled name name
for(Part part : parts) {
if (part.getName().startsWith(MyFile)) {
String filename = getFileName(part);
if (filename.length()>2) {
String temp= new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new java.util.Date().getTime());
filename=temp+"."+filename;
part.write(savaPath+"\\"+filename);//write() Method . You can directly write the uploaded file to disk
}
filenames+=filename+"/";// Multiple files , The filenames Save all file names and store them in the database
}
}
return filenames; // To return , Used to store in the database
}
Focus on the multi file upload process :
chart 1 The file name and... Selected by the front end input Labeled name name , There are three name=photo Of , There is one name=pic In the middle .
chart 2 Printed in the process of background processing files head Information and file name , Only found name=photo Your file was received .
Through this case, I think Key points Yes. , Only the back-end part.getName().startsWith(MyFile) Satisfaction is input Labeled name Named part Will accept the data .
Heavy focus, little five 、 The latest method of uploading single file and multiple files
tomcat8 Use servlet3.0 Upload files , There's a way getSubmittedFileName() Get the file name directly , There's no need to intercept so much trouble .
/*
One 、 The date data of the form is converted to sql Date format dataTrans(String sr0)
1、 Convert the date in string format of the form to java Date format for
2、 take java The date format of is converted to sql Date format for
Two 、 Save the uploaded image to the specified storage path savaFile(), Here is a single file upload
*/
package com.jdbc.utils;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.imageio.IIOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class JdbcFileDateUtil {
// Date format conversion tool
public static java.sql.Date dataTrans(String sr0) {
// Construct the object according to the string pattern specified by the parameter . Realize the relevant conversion between date type and string
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date sr1 =new java.util.Date();
try {
sr1=sdf.parse(sr0);// Is used to String Type conversion to Date type
} catch (ParseException e) {
e.printStackTrace();
}
//getTime Gets the distance of the current object 1970 year 1 month 1 Japan 0 when 0 branch 0 Milliseconds in seconds
return new java.sql.Date((sr1.getTime()));
}
// Save the file selected for form upload to the upload file path specified by the server
// It is applicable to both cases whether there are uploaded files or not , If the file is not uploaded, it will be empty .
//1. Single file upload
public static String savaFile(String MyFile,HttpServletRequest request) throws ServletException,SQLException, IOException {
String savaPath = "D:\\【1】 School professional courses \\ Junior year \\Web Back end development technology \\uploadFile";
Part part =request.getPart(MyFile);
//tomcat8 Use servlet3.0 Upload files , There's a way getSubmittedFileName Get the file name directly , There's no need to intercept so much trouble
String filename = part.getSubmittedFileName();
if (filename.length()>2) {
// Add a timestamp to the file name , Prevent duplicate files .
String temp= new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new java.util.Date().getTime());
filename=temp+"."+filename;
part.write(savaPath+"\\"+filename);//write() Method . You can directly write the uploaded file to disk
}
System.out.println(filename);
return filename;
}
//2. Upload multiple files
public static String savaFiles(String MyFile,HttpServletRequest request) throws ServletException,SQLException, IOException {
String savaPath = "D:\\【1】 School professional courses \\ Junior year \\Web Back end development technology \\uploadFile";
// From the front end form Get all file data in and store it in a list in
List<Part> parts = (List<Part>) request.getParts();
String filenames ="";
// Loop through the file , Each loop gets the name of a file and writes the file data to disk
for(Part part : parts) {
// Get current part Point to the input Labeled name, Only name In order to MyFile Can enter the operation of getting file name only if it starts with the value of ,
// Or jump to the next part, there part.getName().startsWith(MyFile) The key point is to understand and combine the front-end input Of name Value understanding
// startsWith() The parameter of is the corresponding to the upload folder input Labeled name name
if (part.getName().startsWith(MyFile)) {
String filename = part.getSubmittedFileName();// Get the current part The file name that points to
if (filename.length()>2) {
String temp= new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new java.util.Date().getTime());
filename=temp+"."+filename;
part.write(savaPath+"\\"+filename);//write() Method . You can directly write the uploaded file to disk
}
filenames+=filename+"/";// Multiple files , The filenames Save all file names and store them in the database
}
}
return filenames; // To return , Used to store in the database
}
}
版权声明
本文为[Jiugui wine!!!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210556006860.html
边栏推荐
- Azkaban recompile, solve: could not connect to SMTP host: SMTP 163.com, port: 465 [January 10, 2022]
- LeetCode异或运算
- R language ggplot2 visual facet_wrap, and use the lineheight parameter to customize the height of the facet icon tab (gray label bar)
- php参考手册String(7.2千字)
- [H264] hevc H264 parsing and frame rate setting of the old version of libvlc
- Use test of FFT and IFFT library functions of TI DSP
- R language uses econocrats package to create microeconomic or macroeconomic map, visualize indifference function indifference curve, customize calculation intersection, and customize the parameters of
- kibana 报错 server is not ready yet 可能的原因
- 仓库管理数据库系统设计
- How to do product innovation—— Exploration of product innovation methodology I
猜你喜欢
LeetCode动态规划训练营(1~5天)
php参考手册String(7.2千字)
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)
Fundamentals of network communication (LAN, Wan, IP address, port number, protocol, encapsulation and distribution)
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
【文本分类案例】(4) RNN、LSTM 电影评价倾向分类,附TensorFlow完整代码
Kubernetes introduction to mastery - ktconnect (full name: kubernetes toolkit connect) is a small tool based on kubernetes environment to improve the efficiency of local test joint debugging.
Leetcode XOR operation
MySQL advanced lock - overview of MySQL locks and classification of MySQL locks: global lock (data backup), table level lock (table shared read lock, table exclusive write lock, metadata lock and inte
【数值预测案例】(3) LSTM 时间序列电量预测,附Tensorflow完整代码
随机推荐
IIS data conversion problem: 16bit to 24bit
R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
Computing the intersection of two planes in PCL point cloud processing (51)
R language survival package coxph function to build Cox regression model, ggrisk package ggrisk function and two_ Scatter function visualizes the risk score map of Cox regression, interprets the risk
nc基础用法2
Shanda Wangan shooting range experimental platform project - personal record (IV)
Kubernetes introduction to mastery - ktconnect (full name: kubernetes toolkit connect) is a small tool based on kubernetes environment to improve the efficiency of local test joint debugging.
PCL点云处理之基于PCA的几何形状特征计算(五十二)
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (VII)
MySQL数据库 - 数据库和表的基本操作(二)
Use test of FFT and IFFT library functions of TI DSP
Physical meaning of FFT: 1024 point FFT is 1024 real numbers. The actual input to FFT is 1024 complex numbers (imaginary part is 0), and the output is also 1024 complex numbers. The effective data is
考研英语唐叔的语法课笔记
Kubernetes getting started to proficient - install openelb on kubernetes
Leetcode dynamic planning training camp (1-5 days)
【目标跟踪】基于帧差法结合卡尔曼滤波实现行人姿态识别附matlab代码
R language uses timeroc package to calculate the multi time AUC value of survival data under competitive risk, uses Cox model and adds covariates, and R language uses the plotauccurve function of time
基于pytorch搭建GoogleNet神经网络用于花类识别
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
Fundamentals of programming language (2)