Turn: servlet+jsp implementation of image or file upload function specific ideas and code

Source: Internet
Author: User

First, we create a new Web project that creates a new 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 hold the uploaded resources.

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


<%@ 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 is 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 image 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.
After that, we're going to write 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 {
@SuppressWarnings ("Unchecked")
@Override
protected void Service (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Req.setcharacterencoding ("Utf-8");
Resp.setcontenttype ("Text/html;charset=utf-8");
Providing configuration information for a parsing class
Diskfileitemfactory factory = new Diskfileitemfactory ();
To create an instance of a resolved class
Servletfileupload SFU = new Servletfileupload (factory);
Start parsing
Sfu.setfilesizemax (1024*400);
The 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 to the file
A folder under upload to get 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);
The method on some platforms (operating system) will return the 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 in the database

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

}
}

Because the code has been commented in detail, so I believe you can basically pass the process. One thing to note is the setting that resolves the size of the instance space. We hope that the uploaded file will not be infinitely large, so set the


. Setfilesizemax (1024*400);

Here we can also set it as a condition to submit an error prompt to the page when the file is larger than the maximum value. Alternatively, you can read the suffix of the selected file to filter out the types that can be uploaded. The code expands on its own, not in detail.

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

After the upload is over, make the page go to the Upload Success page ok.html. When the user sees this page, it means that you have implemented the upload function for the file.

Article Address: http://www.jb51.net/article/36235.htm

Turn: servlet+jsp implementation of image or file upload function specific ideas and code

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.