At present, both blog forums and enterprise offices cannot do without sharing resources. 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 postCopy codeThe Code is 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">
<Html>
<Head>
<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">
-->
</Head>
<Body>
<Form action = "/upload/UpLoad" method = "post" enctype = "multipart/form-data">
Select the uploaded image or file: <input type = "file" name = "fileName"/> <input type = "submit" value = "Upload"/>
</Form>
</Body>
</Html>
We can see that the data is submitted to the upload/UpLoad under the project.
Then we will compile this servlet -- UpLoad. javaCopy codeThe Code is 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 ();
// Create a DNS 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 <FileItem> items = sfu. parseRequest (req );
// Differentiate form fields
For (int I = 0; I <items. size (); I ++ ){
FileItem item = items. get (I );
// IsFormField is true, indicating that this is not a file upload form field
If (! Item. isFormField ()){
ServletContext sctx = getServletContext ();
// Obtain the physical path for storing files
// A folder under upload gets the folder found by the current online user
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 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 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, SetCopy codeThe Code is 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 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.