File upload is a very common function on the website. You have to parse the request parameters directly using Servlet to obtain uploaded files, which is quite troublesome. Therefore, you generally choose to use apache open source tool, common-fileupload. This jar package can be found on the official website of apache, or under the lib folder of struts. The function of struts upload is based on this implementation.
common-fileupload depends on the common-io package, so you also need to download this package. Then import it under your project path.
Use code as follows
package oop.hg.ytu.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oop.hu.ytu.dao.UploadDomain; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class Upload extends HttpServlet { /** * Handle user upload request*/ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String describe = request.getParameter("describe"); DiskFileItemFactory factory = new DiskFileItemFactory(); @SuppressWarnings("deprecation") String path = request.getRealPath("/upload");//Set disk buffer path factory.setRepository(new File(path)); factory.setSizeThreshold(1024*1024);//Set the create buffer size ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1);//Set the upload file limit size, -1 unlimited try { @SuppressWarnings("unchecked") List<FileItem> list = upload.parseRequest(request); String va = null; for(FileItem item : list){ // String name = item.getFieldName(); if(item.isFormField()){//Judge whether it is a file stream va = item.getString("UTF-8"); // System.out.println(name+"="+va); /// request.setAttribute(name, value); }else{ String value = item.getName();// will pass the full path name int start = value.lastIndexOf("//"); String fileName = value.substring(start+1); // request.setAttribute(name, fileName); InputStream in = item.getInputStream(); UploadDomain dao = new UploadDomain(); //item.write(new File(realPath,fileName)); int index = fileName.lastIndexOf("."); String realFileName = fileName.substring(0,index); String type = fileName.substring(index+1); dao.insert(in, realFileName,type,va);//Put into the database} } } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Here we determine whether it is the uploaded stream or parameters in the form, such as submitting information in the text box, and then insert them into the database. The database insertion code is as follows
package oop.hu.ytu.dao; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import oop.hg.ytu.utils.JdbcUtils; /** * Provide file upload support* @author Administrator * */ public class UploadDomain { /** * Put the uploaded file into the database*/ public void insert(InputStream in, String fileName, String type,String describe) throws Exception{//Write an image to the database Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; System.out.println(describe); try { // 2. Establish a connection conn = JdbcUtils.getConnection(); // 3. Create a statement String sql = "insert into fileupload(file,filename,type,des) values (?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setBlob(1, in); ps.setString(2, fileName); ps.setString(3, type); ps.setString(4, describe); // 4. Execute the statement ps.executeUpdate(); in.close(); } finally { JdbcUtils.free(rs, ps, conn); } } } You may encounter the default database price size limit. You need to change the following configuration under my.ini under mysql installation directory.
[mysqld]
max_allowed_packet=64M
That's all. Of course, pay attention to the encoding format. Upload the file and get it done. Another thing is that one of my column names is set to describe, and the result is that I have conflicted with Mysql reserved words, and information cannot be inserted. You must pay attention to it in the future.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.