当前位置:网站首页>The second method of file upload in form form is implemented by fileitem class, servletfileupload class and diskfileitemfactory class.
The second method of file upload in form form is implemented by fileitem class, servletfileupload class and diskfileitemfactory class.
2022-04-23 20:14:00 【Jiugui wine!!!】
Use commons-fileupload-1.4-bin.zip To get a file with a file stream form The form data .
Problem analysis :
Current end form When the form transfers data to the back end , There will be a very difficult problem : Is there any file data in the data ?? Because there is a different way to deal with it . Design the front-end and use it now Ajax Application Technology , The back end automatically judges when receiving the request form Whether the form data has file data , If there is file data, it is necessary to process the file stream and save it to the specified path .
So how to judge form Does the data from the form contain a file stream ? The ideas and tools used here are FileItem class 、ServletFileUpload class 、DiskFileItemFactory class .
Using these three tools, you can put the front end form All the data in the form is divided into one by one FileItem object , Every data is an object , In this way, we can use the loop to judge whether each data is file data , I'm going to use it directly here if Conditional statements implement , If it is a file, the data should be saved to the path , If it's not file data, use the function fileItem.getFieldName() hold name Save the name of to the database statement sql Field name string in strfiestr1 in ; Use fileItem.getString("utf-8") Save data to database statement sql Medium value in , I named this string strvalSTR1. This is a parameter to prepare for the later modular insertion of data into the database . That is to say , Every time you take one, put fileItem.getFieldName() Value as sql Field name of the command string , hold fileItem.getString The value of sql Command string value Internal value .
FileItem class
It is mainly used to process the data from the front end
ServletFileUpload class
It is mainly used to judge whether the front-end data is mime By way of agreement
DiskFileItemFactory class
It is mainly used to limit the size of uploaded files
union ServletFileUpload Generate file factory , And save to FileItem Type of List in , In this way, you can judge whether it is file data one by one .
DiskFileItemFactory factory1=new DiskFileItemFactory();// originate :commons-fileupload-1.4.jar factory1.setSizeThreshold(1024*1024*20);// Set the number of bytes used in memory ServletFileUpload uploadf1=new ServletFileUpload(factory1); // Create a file factory uploadf1.setHeaderEncoding("utf-8");// It can only solve the garbled Chinese characters in the file name or path java.util.List<FileItem> fileItemList; fileItemList = uploadf1.parseRequest(request); for(FileItem fileItem :fileItemList ){ }
One 、 FileItem The five most important methods of class
fileItem.isFormField() Method for judgment FileItem Class object encapsulates the data as a plain text form field , Or a file form field , If it is a normal form field, it returns true, Otherwise return to false.
fileItem.getName() Method is used to obtain the file path name of the uploaded file , We have to deal with the name later .
fileItem.getFieldName Method to get input Labeled name value .
fileItem.getString() Method is used to get the data value of the current object , namely input What the user enters in the tag .
fileItem.writer() Method is used to write the uploaded file to disk .
Two 、ServletFileUpload class
ServletFileUpload.isMultipartContent(request) Method is used to judge whether the data transmitted from the front end is mime agreement , That is to judge whether the data transmitted this time contains file data .enctype="multipart/form-data"
3、 ... and 、DiskFileItemFactory class
factory1.setSizeThreshold(1024*1024*20);// Set the number of bytes used in memory
Four 、 Combining the above technologies , The front end can be realized automatically form Form data can be saved to the database whether it contains files or not .
Tool class code :
package com.jdbc.utils;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.Connection;
public class FormPostUtil {
public void getparm(HttpServletRequest request,HttpServletResponse response, String path1, JSONArray jsonarr1,JSONObject jsonob1,String tablname1) {
String fname1=""; // Reserved file name , Whether or not to use it later , If a file is uploaded , It has value ; No file transfer , It's a null value
// If it is MIME To upload files
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setContentType("text/html;Charset=UTF-8");
String sqlfiestr1=""; This string is used to save sql Of insert Field column name in command , One click
String sqlvalSTR1=""; // This string is used to save sql Of insert In the command vlaue value
DiskFileItemFactory factory1=new DiskFileItemFactory();// originate :commons-fileupload-1.4.jar
factory1.setSizeThreshold(1024*1024*20);// Set the number of bytes used in memory
ServletFileUpload uploadf1=new ServletFileUpload(factory1); // Create a file factory
uploadf1.setHeaderEncoding("utf-8");// It can only solve the garbled Chinese characters in the file name or path
java.util.List<FileItem> fileItemList;
try {
fileItemList = uploadf1.parseRequest(request);
for(FileItem fileItem :fileItemList )
{if(fileItem.isFormField()) // Indicates that it is a normal parameter , It's not a document . The following is a patchwork sql command insert Prepare the string
{ sqlfiestr1=sqlfiestr1+fileItem.getFieldName()+",";
try {
sqlvalSTR1=sqlvalSTR1+"'"+fileItem.getString("utf-8")+"',";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Code it , Otherwise, the Chinese characters taken out may be garbled
}
else // No fileItem.isFormField()), Then the next item is file flow ( Pay attention to the above program structure , Put the file at the end of the form , Otherwise, you will call the processing file to save in the above loop Independent functions
{ fname1=fileItem.getName();// Take out the file name in advance , When saving to the database later, use
savafile(fileItem, path1);// Write the uploaded file into the save path
}
}
// Ready to insert the above data into the database ; call inserttable() function
inserttable("xs", sqlfiestr1, sqlvalSTR1, fname1,tablname1);// To the specified table , Insert the specified field name , Specify the value , Whether to bring files ( If fname1 If it is empty, insert an empty string into the table
PrintWriter out1;
try {
out1 = response.getWriter();
out1.println(jsonob1);
out1.flush();
out1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Modular file saving
private void savafile(FileItem fileItem,String path1) {
String fname1;
fname1=fileItem.getName();
// System.out.println(fname1);
// Remove the previous path , As long as it is followed by a clean file name .
int po=fname1.lastIndexOf("\\");
if(po!=-1)// Indicates that the right slash was found \
{ fname1=fname1.substring(po+1);}
// System.out.println(fname1);
System.out.println(fileItem.getSize());
if(fileItem.getSize()>1024*1024*20) // The file is too big , Refuse to upload
{return; }
if(fname1==null||fname1.equals("")||fileItem.getSize()==0)
{// That means no files have been uploaded , This kind of treatment The advantage is , Users can transfer or not transfer files , It doesn't matter
}
else {
File savefile1=new File(path1,fname1);
try {
fileItem.write(savefile1);// Let's solve the problem of the same name of existing files by ourselves , You can use the system time number , There is little possibility of conflict
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void inserttable(String tablename, String sqlfiestr1,String sqlvalSTR1,String fname1 ,String tablname1) {
if(sqlfiestr1.length()<1||sqlvalSTR1.length()<1) // That means there is no data upload
;
else { // It indicates that there is data upload in the form , In this way, it is necessary to write to the database . The classmates , This laziness The premise of the method is HMTL Controls in the form name It must be the same as the column name of the database table .
String sqlstr1="";
if(fname1==""||fname1.equals(""))// It means that no file has been uploaded
{ // To remove the last comma in the field name string
sqlfiestr1=sqlfiestr1.substring(0,sqlfiestr1.length()-1);
sqlvalSTR1=sqlvalSTR1.substring(0,sqlvalSTR1.length()-1);
sqlstr1="insert into "+tablename+"("+sqlfiestr1+")values("+sqlvalSTR1+")";
}
else // It means that there are documents coming up , File name is not empty . adjustment insert String photo parameters
{ sqlfiestr1=sqlfiestr1+"photo";
int po=fname1.lastIndexOf("\\"); // Keep only the following file names , Don't go ahead
if(po!=-1)// Indicates that the right slash was found \
{ fname1=fname1.substring(po+1);}
sqlvalSTR1=sqlvalSTR1+"'"+fname1+"'";
sqlstr1="insert into "+tablename+"("+sqlfiestr1+")values("+sqlvalSTR1+")";
}
System.out.println(sqlstr1);
Connection con1=(Connection) JdbcConUtil.getConnection();
Statement st1;
try {
st1 = con1.createStatement();
st1.execute(sqlstr1);
JdbcConUtil.close(st1, con1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Need to use json Of jar package 、commons-fileupload Of jar package
https://pan.baidu.com/s/1-xj4pgv61_D5v637FKMd4g?pwd=6666
Extraction code :6666
https://pan.baidu.com/s/1pjVKYmID4edb_mdggMeZzw?pwd=6666
Extraction code :6666
servlet Test code :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JSONArray jsonarr1=new JSONArray();
JSONObject jsonob1=new JSONObject();
String path1="C:\\JAVA3\\uploadfile"; // Specify the server location where the uploaded file is saved
String tablname1="xs";// Specify the name of the table to operate on
if(ServletFileUpload.isMultipartContent(request))// Judgment is not mime By the way
{
new FormPostUtil.getparm(request, response, path1, jsonarr1, jsonob1,tablname1);
}
else {
// Here we deal with data without files , Here is another tool class for inserting data InsertObject Method
BeanUtils.populate(tempCourse, request.getParameterMap());
String sql1 = "insert into course(cno,cname,tno) values(?,?,?)";
JdbcCRUDUtil.InsertObject(sql1, tempCourse);
}
版权声明
本文为[Jiugui wine!!!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210556006829.html
边栏推荐
- R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
- MySQL数据库 - 单表查询(二)
- Introduction to electron Tutorial 4 - switching application topics
- WordPress插件:WP-China-Yes解决国内访问官网慢的方法
- R语言使用timeROC包计算存在竞争风险情况下的生存资料多时间AUC值、使用cox模型、并添加协变量、R语言使用timeROC包的plotAUCcurve函数可视化多时间生存资料的AUC曲线
- R语言ggplot2可视化:ggplot2可视化散点图并使用geom_mark_ellipse函数在数据簇或数据分组的数据点周围添加椭圆进行注释
- The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
- Unity创建超写实三维场景的一般步骤
- AQS learning
- Sqoop imports data from Mysql to HDFS using lzop compression format and reports NullPointerException
猜你喜欢

Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)

如何在BNB鏈上創建BEP-20通證

山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(七)

波场DAO新物种下场,USDD如何破局稳定币市场?

【文本分类案例】(4) RNN、LSTM 电影评价倾向分类,附TensorFlow完整代码

山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(五)

Openharmony open source developer growth plan, looking for new open source forces that change the world!

Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies

Shanda Wangan shooting range experimental platform project - personal record (IV)

An error is reported when sqoop imports data from Mysql to HDFS: sqlexception in nextkeyvalue
随机推荐
The textarea cursor cannot be controlled by the keyboard due to antd dropdown + modal + textarea
An error is reported in the initialization metadata of the dolphin scheduler -- it turns out that there is a special symbol in the password. "$“
[H264] hevc H264 parsing and frame rate setting of the old version of libvlc
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(七)
VeraCrypt文件硬盘加密使用教程
[numerical prediction case] (3) LSTM time series electricity quantity prediction, with tensorflow complete code attached
Cadence Orcad Capture 批量更改元件封装功能介绍图文教程及视频演示
Design of warehouse management database system
R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
PHP reference manual string (7.2000 words)
Local call feign interface message 404
Comment créer un pass BEP - 20 sur la chaîne BNB
Shanda Wangan shooting range experimental platform project - personal record (IV)
WordPress插件:WP-China-Yes解决国内访问官网慢的方法
Devops integration - environment variables and building tools of Jenkins service
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行3
Mysql database - basic operation of database and table (II)
网络通信基础(局域网、广域网、IP地址、端口号、协议、封装、分用)
Electron入门教程4 —— 切换应用的主题
Shanda Wangan shooting range experimental platform project - personal record (V)