servlet+jsp implementation of image or file upload function specific ideas and code _jsp programming

Source: Internet
Author: User
Tags file upload
Now whether it is a blog forum or corporate office, can not be separated from the sharing of resources. Through the way of file upload, and share with you, so as to achieve a wide range of communication and communication between the masses, we can gain more knowledge and experience, but also through the feedback of others to achieve self-improvement and promotion purposes.

Next I will introduce the Web project in this upload function, then how the file is sent from the local to the server? Watch me slow down:
First, we create a new Web project that creates a upload folder in the Webroot directory of the project, so that when we deploy the project to the server, the server also generates a upload folder to store the uploaded resources.

Then, in the Webroot directory to create a new JSP file, the main implementation of the role is to select the uploaded files, submitted to the servlet to deal with
The detailed code is as follows: A form transmits file information via post to the specified servlet
Copy Code code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >
<title>my JSP ' upload.jsp ' starting page</title>
<meta http-equiv= "Pragma" content= "No-cache" >
<meta http-equiv= "Cache-control" content= "No-cache" >
<meta http-equiv= "Expires" content= "0" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
<meta http-equiv= "description" content= "This are my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-->
<body>
<form action= "/upload/upload" method= "post" enctype= "Multipart/form-data" >
Please select the uploaded picture or file: <input type= "file" Name= "FileName"/><input type= "submit" value= "Upload"/>
</form>
</body>

As you can see, we submit the data to the Upload/upload under the project.
And then we're going to write this Servlet--upload.java
Copy Code code as follows:

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 {
@SuppressWarnings ("Unchecked")
@Override
protected void Service (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Req.setcharacterencoding ("Utf-8");
Resp.setcontenttype ("Text/html;charset=utf-8");
Provide configuration information for the parsing class
Diskfileitemfactory factory = new Diskfileitemfactory ();
To create an instance of a parse class
Servletfileupload SFU = new Servletfileupload (factory);
Start parsing
Sfu.setfilesizemax (1024*400);
Data in each form field is encapsulated on a corresponding Fileitem object
try {
list<fileitem> items = sfu.parserequest (req);
Differentiate form fields
for (int i = 0; i < items.size (); i++) {
Fileitem item = items.get (i);
Isformfield is true to indicate that this is not a File Upload form field
if (!item.isformfield ()) {
ServletContext sctx = Getservletcontext ();
Get the physical path of the file to be stored
A folder under upload gets the current online user to find the corresponding folder

String Path = Sctx.getrealpath ("/upload");
SYSTEM.OUT.PRINTLN (path);
Get file name
String fileName = Item.getname ();
System.out.println (FileName);
In some platforms (operating systems), the method returns the path + filename
FileName = filename.substring (Filename.lastindexof ("/") +1);
File File = new file (path+ "\" +filename);
if (!file.exists ()) {
Item.write (file);
Record the name of the uploaded picture in the database

Resp.sendredirect ("/upload/ok.html");
}
}
}
catch (Exception e) {
E.printstacktrace ();
}

}
}

Because the code has been a detailed annotation, so I believe you can basically pass this process. One thing to note is the setting that resolves the size of the instance space. We want the uploaded file to not be infinitely large, so set the
Copy Code code as follows:

. Setfilesizemax (1024*400);

Here we can also set it as a condition to submit an error message to the page when the file is larger than the maximum value. In addition, you can also read the suffix of the selection file to filter out the types that can be uploaded. These codes are extended by yourselves and are no longer in detail.

Through the servlet, the correct files are routed to the upload folder on the server side. Notice here that if you remove the project from Tomcat later, the files will be deleted automatically.

After the upload, the page ok.html to the Upload Success page. When the user sees this page, it indicates that you have implemented the file upload function.
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.