Chapter 10 _ file upload and chapter 10 File Upload
10.1 client Programming
To upload a file, you must use multipart/form-data to set the value of the enctype attribute of the HTML form, as shown below:
<form action="action" enctype="multipart/form-data" method="post"> Select a file<input type="file" name="fieldName" /> <input type="submit" value="Upload" /> </form>
10.2 server-side Programming
The server-side File Upload programming in Servlet mainly involves the MultipartConfig annotation type and javax. servlet. http. Part interface.
The Servlet that processes the uploaded file must be marked with @ MultipartConfig. MultipartConfig can have the following attributes, which are optional.
MaxFileSize indicates the maximum file size that can be uploaded. Files that exceed the set value will be rejected. The default value is-1, indicating no restriction.
MaxRequestSize indicates the maximum capacity allowed for multiple HTTP requests. Its default value is-1, which is unrestricted.
Location: the uploaded file is saved to the specified Location on the disk. You can call the write method in the Part to use it.
FileSizeThreshold, set an overflow size. After this value is exceeded, the uploaded files will be written to the disk.
In a request composed of multiple parts, each form field, including non-file fields, is converted into a Part. The HttpServletRequest interface defines the following methods to process multiple parts of the request:
Part getPart (java. lang. String name)
Returns the Part associated with the specified name.
Java. util. Collection <Part> getParts ()
Returns all parts in this request.
The Part interface also has the following methods:
Java. lang. String getName ()
Obtain the name of this part, such as the name of the relevant form field
Java. lang. String getContentType ()
If the Part is a file, the content type of the Part is returned. Otherwise, null is returned.
Java. util. Collection <java. lang. String> getHeaderNames ()
Returns the names of all headers in this Part.
Java. lang. String getHeader (java. lang. String headerName)
Returns the value of the specified header name.
Java. util. Collection <java. lang. String> getHeaders (java. lang. String headerName)
Returns the names of all headers in this Part.
Void write (java. lang. String path)
Write uploaded files to the disk. If path is an absolute path, it is written to the specified path. If path is a relative path, it is written to the specified path relative to the location attribute value of the MultiConfig annotation.
Void delete ()
Delete the storage corresponding to the file, including related temporary files.
Java. io. InputStream getInputStream ()
Return the content of the uploaded file in the form of inputStream
If the relevant HTML input is a file input element, the Part will return these headers:
Content-type: contentType
Content-disposition: form-data; name = "fieldName"; fileName = "fileName"
For example, when a file named document.txt is uploaded to the domain, the relevant department will also have these headers:
Content-type: text/plain
Content-disposition: form-data; name = "document"; filename={note.txt"
If no file is selected, a Part is still created for the file domain, but the related header is as follows:
Content-type: application/octet-stream
Content-disposition: form-data; name = "document"; fileName = ""
The getName of the Part interface returns the name of the domain related to this Part, rather than the name of the uploaded file. To return the latter, you must parse the content-disposition Header in the following format:
Content-disposition: form-data; name = "fieldName"
When processing uploaded files in the Servlet, you must:
1. check whether a Part belongs to a common form field or a file field by checking whether the content-type Header exists in the stone. You can also call the getContentType method or getHeader ("content-type") in the Part to complete the check.
2. If the content-type Header exists, check whether the name of the uploaded file is null. The file name is blank, indicating that a file type domain exists, but no file to be uploaded is selected.
3. If the file exists, you can call the write method in the Part to write data to the disk. An absolute path or a path relative to the location attribute of the MultipartConfig annotation will be passed during the call.
11.3 upload Servlet example
SingleUploadServlet. java
Package app11a. servlet; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. annotation. multipartConfig; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. part; @ WebServlet (urlPatterns = {"/single Upload "}) @ MultipartConfigpublic class SingleUploadServlet extends HttpServlet {private static final long serialVersionUID = 1L; /*** file name obtained through the part * @ param part * @ return */private String getFileName (Part part) {String contentDispositionHeader = part. getHeader ("content-disposition"); String [] elements = contentDispositionHeader. split (";"); for (String element: elements) {if (element. trim (). startsWith ("f Ilename ") {return element. substring (element. indexOf ('=') + 1 ). trim (). replace ("\" "," ") ;}} return null ;}@ Overridepublic void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req. setCharacterEncoding ("UTF-8"); resp. setCharacterEncoding ("UTF-8"); Part part = req. getPart ("filename"); String fileName = getFileName (part); if (fileName! = Null &&! FileName. isEmpty () {part. write (getServletContext (). getRealPath ("/WEB-INF") + "/" + fileName);} resp. setContentType ("text/html"); PrintWriter writer = resp. getWriter (); writer. print ("<br/> Upload file name:" + fileName); writer. print ("<br/> Size:" + part. getSize (); String author = req. getParameter ("author"); writer. print ("<br/> Author:" + author );}}
SingleUplpad. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%>
11.4 MultipleUploadsServlet. java
Package app11a. servlet; import java. io. IOException; import java. io. printWriter; import java. util. collection; import javax. servlet. servletException; import javax. servlet. annotation. multipartConfig; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. part; @ WebSer Vlet (urlPatterns = {"/multipleUploads"}) @ MultipartConfigpublic class MultipleUploadsServlet extends HttpServlet {private static final long serialVersionUID = 1L; private String getFileName (Part part) {String contentDispositionHeader = part. getHeader ("content-disposition"); String [] elements = contentDispositionHeader. split (";"); for (String element: elements) {if (element. trim (). startsWith ("filename ")){ Return element. substring (element. indexOf ('=') + 1 ). trim (). replace ("\" "," ") ;}} return null;} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html"); PrintWriter writer = response. getWriter (); Collection <Part> parts = request. g EtParts (); for (Part part: parts) {// you can use getContentType to determine whether it is a file domain if (Part. getContentType ()! = Null) {String fileName = getFileName (part); // obtain if (fileName! = Null &&! FileName. isEmpty () {part. write (getServletContext (). getRealPath ("/WEB-INF") + "/" + fileName); writer. print ("<br/> Uploaded file name:" + fileName); writer. print ("<br/> Size:" + part. getSize () ;}} else {String partName = part. getName (); String fieldValue = request. getParameter (partName); writer. print ("<br/>" + partName + ":" + fieldValue );}}}}
MultipleUploads. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%>
Run:
11.5 upload Client
In this example, javascript and HTML5 File APIs are used to provide progress bars to report the upload progress.
Html5.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
Baidu wants to upload files
Do not upload any documents that involve copyright infringement without authorization, unless the documents are completely created by you
Your document will be removed if any infringing content is involved
A maximum of 10 documents can be uploaded each time. Each document cannot exceed 20 mb.
To ensure normal display of documents, we support uploading documents in the following formats
MS Office documentation doc, docx ppt, pptx xls, xlsx caf pot pps rtf
WPS office series wps et dps
PDF
Plain text txt
EPUB epub
Reference: from Baidu Library
File Upload
When uploading a file, first find the file to be uploaded through the upload control, then obtain the file size, and finally write the file to the database in the form of a stream. The specific code is:
Private void Btn_ OK _Click (object sender, System. EventArgs e)
{
String name = name_TextBox.Text;
// Receives the uploaded file
Stream fileStream = File1.PostedFile. InputStream;
// Obtain the size of the uploaded file in bytes.
Int length = File1.PostedFile. ContentLength;
Byte [] wordData = new byte [length];
// Read the byte from the stream and write it into wordData
Int n = fileStream. Read (wordData, 0, length );
// Obtain the current time
DateTime time = DateTime. Now;
// Connect to the database
SqlConnection conn = new SqlConnection ();
Conn. ConnectionString = "workstation id = TIANCHUNZHU; packet size = 4096; integrated security = SSPI; data source = TIANCHUNZHU; persist security info = False; initial catalog = test ";
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = conn;
Cmd. CommandText = "insert into word (fileName, postTime, fileContent) values (@ fileName, @ postTime, @ fileContent )";
SqlParameter nameParam = new SqlParameter ("@ fileName", System. Data. SqlDbType. VarChar, 50 );
NameParam. Value = name;
Cmd. Parameters. Add (nameParam );
SqlParameter timeParam = new SqlParameter ("@ postTime", System. Data. SqlDbType. DateTime, 8 );
TimeParam. Value = time;
Cmd. Parameters. Add (timeParam );
// Add a word file
... The remaining full text>