当前位置:网站首页>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