1.1. jsp file Upload 1.1.1. Create a new Web project 1.1.2. Upload page index.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " pageencoding=" Utf-8 "%><! DOCTYPE html>
|
1.1.3. File Upload processing Fileuploadservlet.java
Package com.jsp.file.upload.servlet; Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.io.RandomAccessFile; Import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse; @WebServlet ("/fileuploadservlet") public class Fileuploadservlet extends HttpServlet {private static final long SE Rialversionuid = 1L; public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { InputStream InputStream = Request.getinputstream (); String Realpath = Request.getservletcontext (). Getrealpath ("Upload"); File Tempfile = new file (Realpath, "temp.tmp"); FileOutputStream fos = new FileouTputstream (Tempfile); byte[] buffer = new byte[1024]; int len = 0; while ( -1! = (len = inputstream.read (buffer))) {fos.write (buffer, 0, Len); } randomaccessfile randomfile = new Randomaccessfile (tempfile, "R"); Randomfile.readline (); String contentdisposition = Randomfile.readline (); String filename = contentdisposition.substring (Contentdisposition.indexof ("filename=\"), Contentdisposition.lastindexof ("\" ")); filename = filename.replace ("filename=\", "" "); Prevent Chinese garbled filename = new String (filename.getbytes ("iso-8859-1"), "UTF-8"); SYSTEM.OUT.PRINTLN (filename); Randomfile.seek (0); Long start = 0; int forth = 1; while ( -1! = (len = Randomfile.readbyte ()) && (forth<=4)) {if (len = = ' \ n ') { Start = Randomfile.getfilepointer (); forth++; }} fos.close (); Inputstream.close (); File SaveFile = new file (realpath,filename); Randomaccessfile randomaccessfile = new Randomaccessfile (saveFile, "RW"); Randomfile.seek (Randomfile.length ()); Long endposition = Randomfile.getfilepointer (); int j = 1; while ((EndpositioN >= 0) && J <= 2) {endposition--; Randomfile.seek (endposition); if (randomfile.readbyte () = = ' \ n ') {j + +; }} randomfile.seek (start); Long startPoint = Randomfile.getfilepointer (); while (StartPoint < endPosition-1) {Randomaccessfile.write (Randomfile.readbyte ()); StartPoint = Randomfile.getfilepointer (); } randomaccessfile.close (); Randomfile.close (); Tempfile.delete (); System.out.println ("File upload succeeded"); } }
|
1.1.4. File Upload Instance
An example of the contents of a temporary file obtained in the above code,
------WEBKITFORMBOUNDARYDUEEAVH7AOONF8SX Content-disposition:form-data; Name= "File1"; Filename= "new text document. txt" Content-type:text/plain Aa Bb Cc ------webkitformboundarydueeavh7aoonf8sx-- |
JSP implementation File Upload