The Method of Uploading File by servlet+JSP+mysql

  • 2021-08-17 00:40:45
  • OfStack

This paper describes the method of servlet+JSP+mysql to upload files. Share it for your reference, as follows:

1. Basic operation of file upload:

1. Setting of form attribute enctype

Differences between multipart/form-data and application/x-www-form-urlencoded

The enctype attribute of the FORM element specifies the encoding type used when the form data is submitted to the server, and the default value is "application/x-www-form-urlencoded".

However, this encoding is inefficient when sending large amounts of text, text containing non-ASCII characters, or binary data to the server.

When uploading files, the encoding type used should be "multipart/form-data", which can send both text data and binary data upload.

Browser terminal < form > The ENCTYPE attribute value of the form is multipart/form-data, which tells us that the transmitted data should use multimedia transmission protocol. Because multimedia transmits a large amount of data, it is stipulated that the uploaded file must be post method. < input > The type property of must be file.

Implementation process:


package cn.csdn.web.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import cn.csdn.web.c3p0.DBManager_c3p0;
public class Upload2Servlet extends HttpServlet {
/**
* 
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
try {
// Instantiation 1 File factory  
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setRepository(new File("C:\\osp"));
String paramName=null;
String paramValue=null;
// Configuring Upload Components ServletFileUpload 
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024*1024);
// From request Get a list of all uploaded domains  
List<FileItem> list=upload.parseRequest(request);
for(FileItem item:list){
// If it is a file domain of an upload domain  
if(item.isFormField()){
// Form common input items 
paramName = item.getFieldName(); // Uploaded in Name
// String paramValue=item.getString();
// paramValue=new String(paramValue.getBytes("iso8859-1"),"UTF-8");
paramValue=item.getString("UTF-8");
System.out.println(paramName+"="+paramValue);
}else{
// Upload file processing 
String fileName = item.getName();
fileName=fileName.substring(fileName.lastIndexOf("\\")+1); // Intercept extension  
System.out.println("name="+fileName);
if(!fileName.equals("")){
// fileName=refactorFileName(fileName);
InputStream in=item.getInputStream();
File file = new File("c:\\"+fileName);
FileOutputStream os=new FileOutputStream(file);
byte[] buf = new byte[1024];
int len=0;
while((len=in.read(buf))>0){
os.write(buf,0,len);
}
os.flush();
os.close();
in.close();
item.delete();
request.setAttribute("message", " File uploaded successfully ");
try {
DataSource ds = DBManager_c3p0.getDataSource();
QueryRunner runner = new QueryRunner(ds);
String sql = "insert into user(name,file) values(?,?)";
Object[] params = {paramValue,fileName};
runner.update(sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch(FileSizeLimitExceededException e1){
e1.printStackTrace();
request.setAttribute("message", " The file size is too large ");
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("message", " File upload failed ");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
// public String refactorFileName(String fileName){
// return UUID.randomUUID().toString()+"_"+fileName;
// }
}

2. Pay attention to the following when uploading files:

Pay attention to coding problems to prevent Chinese garbled codes. One kind is listed above
Others have temporary file resolution problems and temporary file deletion problems
Resolve the problem that no file name is specified
Determining whether the fetched filename is empty
Save path problem
For example, the slash "/" should be used when representing url resources
For example, use the slash "\\" when representing the hard disk path
For server security, uploaded files should not be directly accessible to users, and are usually stored in the WEB-INF directory of the application, or in a directory not managed by the WEB server

I hope this article is helpful to everyone's jsp programming.


Related articles: