Servlet + Jsp Implementation of the image or file upload function specific ideas and code

Source: Internet
Author: User
In the web Project, how does one send files locally to the server? Next, let's introduce Servlet + Jsp to implement the file upload function, if you are interested, you can refer to the following: Resource Sharing is indispensable for both blog forums and enterprise offices. By uploading files, we can share them with you to achieve extensive communication and communication among the masses. We can gain more knowledge and experience from them, it can also achieve self-improvement and improvement through others' feedback.

Next I will introduce this upload function in the web project. How does one send files locally to the server? Let's take a look:
First, we create a new web project and create a new upload folder under the WebRoot directory of the project, so that when we deploy the project to the server, the server also generates an upload folder to store the uploaded resources.

Then, create a jsp file under the WebRoot directory. The main function is to select the uploaded file and submit it to the servlet for processing.
The Code details are as follows: a form transfers the file information to the specified servlet through post

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>     My JSP 'upload.jsp' starting page 
  
  
  
  
  
      

We can see that the data is submitted to the upload/UpLoad under the project.
Then we will compile this servlet -- UpLoad. java

Package load; import java. io. file; import java. io. IOException; import java. io. printWriter; import java. util. list; import javax. servlet. servletContext; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; public class UpLoad extends HttpServlet {@ brief ("unchecked") @ Override protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req. setCharacterEncoding ("UTF-8"); resp. setContentType ("text/html; charset = UTF-8"); // provides the configuration information DiskFileItemFactory factory = new DiskFileItemFactory () for the parsing class (); // create a resolution class instance ServletFileUpload sfu = new ServletFileUpload (factory); // start parsing sfu. setFileSizeMax (1024*400); // data in each form field is encapsulated into a corresponding FileItem object. try {List
 
  
Items = sfu. parseRequest (req); // differentiate form fields for (int I = 0; I <items. size (); I ++) {FileItem item = items. get (I); // if (! Item. isFormField () {ServletContext sctx = getServletContext (); // obtain the physical path of the file to be stored // a folder under upload. The current online user can find the corresponding folder String path = sctx. getRealPath ("/upload"); System. out. println (path); // get the file name String fileName = item. getName (); System. out. println (fileName); // on some platforms (Operating Systems), this method returns path + file name fileName = fileName. substring (fileName. lastIndexOf ("/") + 1); File file = new File (path + "\" + fileName); if (! File. exists () {item. write (file); // record the name of the uploaded image to the database resp. sendRedirect ("/upload/OK .html") ;}}} catch (Exception e) {e. printStackTrace ();}}}
 

Because the code has been commented out in detail, we believe that you can basically upload this process. Note that the setting of the Instance space size is resolved. We hope that the file to be uploaded will not be infinitely large. Therefore, Set

.setFileSizeMax(1024*400);

Here we can also set it as a condition to submit an error message to the page when the file exceeds the maximum value. In addition, you can also read the suffix of the selected file to filter out the types that can be uploaded. These codes can be expanded on your own and will not be discussed in detail.

Send the correct file to the upload folder on the server through servlet. Note that these files will be automatically deleted after the project is removed from tomcat in the future.

After uploading, turn the page to the success page OK .html. When you see this page, you have implemented the file upload function.


For more details about how to use Servlet + Jsp to upload images or files, refer to PHP's Chinese website!

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.