Edit the page upload.html of upload file
Note: GET cannot be used when uploading POST (GET cannot upload files)
The form enctype property should be set to multipart/form-data. (Indicates that the submitted data is a binary file)
upload.html
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>File Upload</title></head><body> <form action="UploadPhotoServlet" method="POST" enctype="multipart/form-data"> Character name:<input type="text" name="heroName"/><br> Upload avatar:<input type="file" name="filepath"/><br> <input type="submit" value="upload"> </form></body></html>
UPloadPtotoServlet file upload class--development of upload function
Put the two jar packages commons-io-1.4.jar and commons-fileupload-1.2.2.jar in the WEB-INF/lib directory.
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;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;/** * Servlet implementation class UploadPhotoServlet */@WebServlet("/UploadPhotoServlet")public class UploadPhotoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadPhotoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub// response.getWriter().append("Served at: ").append(request.getContextPath()); String filename=null; DiskFileItemFactory factory=new DiskFileItemFactory(); //Disk file entry factory ServletFileUpload upload=new ServletFileUpload(factory); //Responsible for processing uploaded file data and encapsulating each input item in the form into a fileitem object //Set the uploaded file size to 10M factory.setSizeThreshold(2*1024*1024); List items=null; try { //parse parses items=upload.parseRequest(request); //Get a List object that saves all uploaded content} catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } Iterator iter=items.iterator(); //Iterate over the uploaded file data while(iter.hasNext()){ FileItem item=(FileItem) iter.next(); if(!item.isFormField()){ //If it is not uploaded //Create the avatar file based on the timestamp filename=System.currentTimeMillis()+".jpg"; //Get the upload folder through getrealpath. If the project exists, it will not exist under the current project, create the project folder//Picture folder String photoFolder=request.getServletContext().getRealPath("uploaded"); File f=new File(photoFolder,filename); f.getParentFile().mkdirs(); //If the parent folder does not exist, it will be created automatically//Get the file uploaded by the browser through item.getInputStream() InputStream is = item.getInputStream(); //Read the file in//Copy the file FileOutputStream fos=new FileOutputStream(f); //Show byte[] b=new byte[2*1024*1024] on the interface; int len=0; while((len=is.read(b))!=-1){ fos.write(b, 0, len); } fos.close(); }else{ System.out.println(item.getFieldName());//heroName String value=item.getString(); value=new String(value.getBytes("ISO-8859-1"), "UTF-8"); System.out.println(value); //Mulberry} } String html="<img width='200' height='150' src='uploaded/%s'/>"; response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.format(html, filename); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}Running results:
Summarize
The above is the implementation code for uploading files to the server and displaying functions accordingly. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!