JSP practical tutorial-Implementation of the simple File Upload Component (with source code ),

Source: Internet
Author: User

JSP practical tutorial-Implementation of the simple File Upload Component (with source code ),

Preface

This article mainly introduces how to implement the JSP simple File Upload Component. I will share it with you for your reference. I will not talk about it below. Let's take a look at the details.

File Upload, including but not limited to Image Upload, is a common use case in Web development. I believe you have written code related to this aspect more or less. For Java, if a file is uploaded, it must be called Apache Commons FileUpload, and SmartUpload. Even more, Servlet 3.0 uploads files to the JSR standard, so that you can configure the upload in the Servlet through several annotations without relying on any components. The use of third-party components or Servlet components is powerful, but JSP alone can also complete the task, and is short and refined, isn't it beautiful? The methods implemented in this article are purely Based on JSP code, without Servlet and specialized Class (. java). The implementation method is purely Based on JSP, and there is no high technical difficulty. You can directly deploy it during actual use.

The number of lines of code for the Operation component cannot exceed 10. You only need to perform the following steps:

  • Generate component instances
  • Set instance Properties
  • Call upload/download Methods
  • Process call results

First, upload the page. In this example, it is a static HTML file.

Shows the successful upload.

Use the form of POST, set ContentType to multipart/form-data, and remember the name attribute of input.

The server code that accepts client requests in action is in action. jsp. Action. jsp<%@include file="Upload.jsp"%>The core Java code is included, and the Upload. jsp file contains another UploadRequest. jsp file. In short, our small Java program contains the UploadRequest Request Information Class, UploadException custom exception class, and the most important Upload class.

<% @ Page pageEncoding = "UTF-8" %> <% @ include file = "Upload. jsp "%> <% UploadRequest ur = new UploadRequest (); // CREATE request information. Set ur here for all parameters. setRequest (request); // The request ur must be input. setFileOverwrite (true); // does the same file name overwrite? True = allow overwriting Upload upload = new Upload (); // The Uploader try {upload. upload (ur);} catch (UploadException e) {response. getWriter (). println (e. toString ();} if (ur. isOk () // response after successful upload. getWriter (). println ("uploaded successfully:" + ur. getUploaded_save_fileName (); else response. getWriter (). println ("Upload Failed! "); %>

The UploadRequest instance is created here. The file upload operation usually adds some restrictions, such as the file type, the total size of the uploaded file, and the maximum size of each file. In addition, as a general component, more problems need to be considered, such: supports custom file storage directories, relative paths and absolute paths, and custom file names. All these configurations are set in UploadRequest.

As for the classes in JSP, I 'd like to talk more about them. In JSP, Java classes can be defined. classes can be static, but cannot have static members. In fact, JSP classes are all internal classes, so defining static is irrelevant. If the static method cannot be defined, the static method is removed from the class body and written,

<%! /*** Get the length occupied by the start data header ** @ param dateBytes * file binary data * @ return */private static int getStartPos (byte [] dateBytes) {...}>

<%! ... %>And<% ... %>Different, the former defines class members.

Good ~ Let's take a look at UploadRequest. jsp to know what the specific configuration is.

<% @ Page pageEncoding = "UTF-8" %> <%! /*** The bean of the upload request, containing all request information * @ author frank **/public static class UploadRequest {/*** maximum file size for upload, the default value is 1 MB */private int MaxFileSize = 1024*1000;/*** directory for saving the file */private String upload_save_folder = "E: \ temp \\"; /* ** indicates whether the upload is successful */private boolean isOk;/* Indicates whether to change the name */private boolean isNewName;/* indicates the name of the uploaded file. If isNewName = false, it is the original upload name */private String uploaded_save_fileName;/*** is the same file name overwritten? True = allow overwriting */private boolean isFileOverwrite = true; private HttpServletRequest request;/*** @ return the maxFileSize */public int getMaxFileSize () {return MaxFileSize ;} /*** @ param maxFileSize the maxFileSize to set */public void setMaxFileSize (int maxFileSize) {MaxFileSize = maxFileSize ;} /*** @ return the upload_save_folder */public String getUpload_save_folder () {return upload_save_fo Lder;}/*** @ param upload_save_folder the upload_save_folder to set */public void setUpload_save_folder (String upload_save_folder) {this. upload_save_folder = upload_save_folder;}/*** @ return the isOk */public boolean isOk () {return isOk ;} /*** @ param isOk the isOk to set */public void setOk (boolean isOk) {this. isOk = isOk;}/*** @ return the isNewName */public boolean isNewName (){ Return isNewName;}/*** @ param isNewName the isNewName to set */public void setNewName (boolean isNewName) {this. isNewName = isNewName;}/*** @ return the uploaded_save_fileName */public String getUploaded_save_fileName () {return uploaded_save_fileName ;} /*** @ param uploaded_save_fileName the uploaded_save_fileName to set */public void setUploaded_save_fileName (String uploaded_save_fileNa Me) {this. uploaded_save_fileName = uploaded_save_fileName;}/*** @ return the isFileOverwrite */public boolean isFileOverwrite () {return isFileOverwrite;}/*** is the same file name overwritten? True = * @ param isFileOverwrite the isFileOverwrite to set */public void setFileOverwrite (boolean isFileOverwrite) {this. isFileOverwrite = isFileOverwrite;}/*** @ return the request */public HttpServletRequest getRequest () {return request ;} /*** @ param request the request to set */public void setRequest (HttpServletRequest request) {this. request = request ;}%>

This is a common java bean. The Upload class completes the Upload logic.

The principle is:

1. The client generates a request data stream for the file to be uploaded and establishes a connection with the server;

2. The server receives the request stream and caches the stream to the memory;

3. The server-side memory outputs files to the specified directory.

The complete Upload. jsp code is as follows.

<% @ Page pageEncoding = "UTF-8" import = "java. io. *" %> <% @ include file = "UploadRequest. jsp" %> <%! Public static class UploadException extends Exception {private static final long serialVersionUID = 579958777177500819L; public UploadException (String msg) {super (msg );}} public static class Upload {/*** upload accepted ** @ param uRequest * Upload POJO * @ return * @ throws UploadException */public UploadRequest upload (UploadRequest uRequest) throws UploadException {HttpServletRequest req = uRequest. getRe Quest (); // obtain the data type String contentType = req. getContentType (); if (! Req. getMethod (). equals ("POST") {throw new UploadException ("POST request required");} if (contentType. indexOf ("multipart/form-data") =-1) {throw new UploadException ("form multipart/form-data not set");} int formDataLength = req. getContentLength (); if (formDataLength> uRequest. getMaxFileSize () {// whether the throw is too large new UploadException ("the file size exceeds the system limit! ");} // Save the uploaded file Data byte dateBytes [] = new byte [formDataLength]; int byteRead = 0, totalRead = 0; try (DataInputStream in = new DataInputStream (req. getInputStream ();) {while (totalRead <formDataLength) {byteRead = in. read (dateBytes, totalRead, formDataLength); totalRead + = byteRead;} catch (IOException e) {e. printStackTrace (); throw new UploadException (e. toString ();} // get the data split string int lastInd Ex = contentType. lastIndexOf ("="); // boundary = ----------------------------- String boundary = contentType. substring (lastIndex + 1, contentType. length (); // --------------------------- 257261863525035 // The length of the Data header at the beginning of the calculation int startPos = getStartPos (dateBytes); // The boundary position int endPos = byteIndexOf (dateBytes, boundary. getBytes (), (dateBytes. length-startPos)-4; // create the file String fileName = uRequest. ge TUpload_save_folder () + getFileName (dateBytes, uRequest. isNewName (); uRequest. setUploaded_save_fileName (fileName); File checkedFile = initFile (uRequest); // write the File try (FileOutputStream fileOut = new FileOutputStream (checkedFile);) {fileOut. write (dateBytes, startPos, endPos-startPos); fileOut. flush (); uRequest. setOk (true);} catch (FileNotFoundException e) {e. printStackTrace (); throw new UploadEx Ception (e. toString ();} catch (IOException e) {e. printStackTrace (); throw new UploadException (e. toString ();} return uRequest ;}} /*** get the length occupied by the start data header ** @ param dateBytes * file binary data * @ return */private static int getStartPos (byte [] dateBytes) {int startPos; startPos = byteIndexOf (dateBytes, "filename = \"". getBytes (), 0); startPos = byteIndexOf (dateBytes, "\ n ". getBytes (), startPos) + 1; // traverse 3 Line Break to data block startPos = byteIndexOf (dateBytes, "\ n ". getBytes (), startPos) + 1; startPos = byteIndexOf (dateBytes, "\ n ". getBytes (), startPos) + 1; return startPos;}/*** search for a byte array in the byte array and return> = 0, -1 * @ param data * @ param search * @ param start * @ return */private static int byteIndexOf (byte [] data, byte [] search, int start) not found) {int index =-1; int len = search. length; for (int I = start, j = 0; I <da Ta. length; I ++) {int temp = I; j = 0; while (data [temp] = search [j]) {// System. out. println (j + 1) + ", value:" + data [temp] + "," + search [j]); // count j ++; temp ++; if (j = len) {index = I; return index ;}} return index ;}/ *** create a directory if no directory is specified; check whether the File can be overwritten ** @ param uRequest * upload POJO * @ return * @ throws UploadException */private static File initFile (UploadRequest uRequest) throws UploadException {File dir = New File (uRequest. getUpload_save_folder (); if (! Dir. exists () dir. mkdirs (); File checkFile = new File (uRequest. getUploaded_save_fileName (); if (! URequest. isFileOverwrite () & checkFile. exists () {throw new UploadException ("the file already exists and cannot be overwritten! ");} Return checkFile;}/*** get the binary data of the file name ** @ param dateBytes * in the POST Body * @ param isAutoName * Whether to customize the name, true = timestamp file name * @ return */private static String getFileName (byte [] dateBytes, boolean isAutoName) {String saveFile = null; if (isAutoName) {saveFile = "2016" + System. currentTimeMillis ();} else {String data = null; try {data = new String (dateBytes, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace (); data = "errFileName";} // get the uploaded file name saveFile = data. substring (data. indexOf ("filename = \" ") + 10); saveFile = saveFile. substring (0, saveFile. indexOf ("\ n"); saveFile = saveFile. substring (saveFile. lastIndexOf ("\") + 1, saveFile. indexOf ("\" ");} return saveFile;} %>

Read stream data to dataBytes through DataInputStream and write it to FileOutputStream. In addition, there are some logic around the configuration.

It is worth mentioning that the default Java Syntax of JSP in Tomcat 7 is still 1.6. The code embedded with the Java 1.7 feature in JSP will throw the "Resource specification not allowed here for source level below 1.7" exception. You need to modify the configuration file in Tomcat/conf/web. xml, find the <servlet> node, and add the following bold Section.Note that jsp nodes are not default nodes (similar ).

<servlet>   <servlet-name>jsp</servlet-name>   <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>   <init-param>    <param-name>fork</param-name>    <param-value>false</param-value>   </init-param>   <init-param>    <param-name>xpoweredBy</param-name>    <param-value>false</param-value>   </init-param> lt;strong>  <init-param>    <param-name>compilerSourceVM</param-name>    <param-value>1.7</param-value>   </init-param>   <init-param>    <param-name>compilerTargetVM</param-name>    <param-value>1.7</param-value>   </init-param></strong>   <load-on-startup>3</load-on-startup>  </servlet> 

Now, a simple File Uploader is complete. However, the disadvantages of this component are quite obvious. I would like to list two items: 1. The memory occupied by the upload stream rather than the disk, so the memory will be tight when uploading large files; 2. multipart File Upload is not supported, that is, only one file can be uploaded at a time.

Source code download: http://xiazai.jb51.net/201707/yuanma/SimpleUpload (jb51.netw..rar

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.