Servlet + JSP + mysql File Upload method, servletmysql

Source: Internet
Author: User

Servlet + JSP + mysql File Upload method, servletmysql

This document describes how to upload files using servlet + JSP + mysql. We will share this with you for your reference. The details are as follows:

I. Basic file upload operations:

1. Set 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. The default value is "application/x-www-FORM-urlencoded ".

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

During file upload, the encoding type used should be "multipart/form-data". It can send text data and upload binary data.

The value of the ENCTYPE of the Browser <form> form is multipart/form-data, which tells us that the transmitted data uses the multimedia transmission protocol. Because the multimedia transmission involves a large amount of data, therefore, the file to be uploaded must be the post method, and the type attribute of <input> 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; pub Lic class Upload2Servlet extends HttpServlet {/*****/private static final long serialVersionUID = 1L; public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); try {// real Example: A file factory DiskFileItemFactory factory = new DiskFileItemFactory (); factory. setRepository (new File ("C: \ osp"); String paramName = null; String paramValue = null; // configure the upload Component ServletFileUpload upload = new ServletFileUpload (factory ); upload. setHeaderEncoding ("UTF-8"); upload. setFileSizeMax (1024*1024); // obtain the List of all upload domains from the request. <FileItem> list = upload. parseRequest (request); for (FileItem item: list) {// if it is If (item. isFormField () {// form normal input item paramName = item. getFieldName (); // Name uploaded to // String paramValue = item. getString (); // paramValue = new String (paramValue. getBytes ("iso8859-1"), "UTF-8"); paramValue = item. getString ("UTF-8"); System. out. println (paramName + "=" + paramValue);} else {// String fileName = item for file uploading. getName (); fileName = fileName. substring (fileName. lastIndexOf ("\") + 1); // intercept the 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_c31_getdata Source (); 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 blocke. printStackTrace () ;}}}} catch (FileSizeLimitExceededException e1) {e1.printStackTrace (); request. setAttribute ("message", "file size too large");} catch (FileUploadException e) {// TODO Auto-generated catch blocke. 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. Note the following when uploading files:

Pay attention to encoding to prevent Chinese garbled characters.
Other problems are solved by temporary files.
Solve the problem that no file name is specified
Determines whether the obtained file name is null.
Saving path
For example, the slash "/" should be used to indicate the url resource.
For example, the slash "\" is used to indicate the hard disk path.
To ensure server security, uploaded files should be inaccessible to users, typically stored in the WEB-INF directory of the application, or directories not managed by the WEB Server

I hope this article will help you with jsp program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.