Servlet實現基本檔案上傳

來源:互聯網
上載者:User

 

實現檔案上傳,表單屬性需要設定為method=”post”,encType=multipart/form-data,在伺服器端通過request.getInputStream()獲得檔案輸入資料流,然後對流進行操作,獲得所需要的內容。

 

 

Html頁面代碼upload.html

<form action="UploadServlet3" method="post" enctype="multipart/form-data">    <input type="file" name="file">    <input type="submit" name="upload"value="上傳"></form>

1.實現基本檔案上傳

Servlet代碼

public class UploadServlet1 extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {           InputStream in = request.getInputStream();           File f = new File("d:/temp","aaa.txt");           FileOutputStream fos = new FileOutputStream(f);           byte[] b = new byte[1024];           int n=0;           while((n=in.read(b))!=-1){              fos.write(b,0,n);           }           fos.close();           in.close();    }}

此方法上傳的檔案開啟後如下:

-----------------------------26962244645705

Content-Disposition: form-data; name="file";filename="a.txt"

Content-Type: text/plain

 

Java Servlet Technology

As soon as the web began to be used for deliveringservices, service providers recognized the need for dynamic content. Applets,one of the earliest attempts toward this goal, focused on using the clientplatform to deliver dynamic user experiences. At the same time, developers alsoinvestigated using the server platform for this purpose. Initially, CommonGateway Interface (CGI) scripts were the main technology used to generatedynamic content. Although widely used, CGI scripting technology has a number ofshortcomings, including platform dependence and lack of scalability. To addressthese limitations, Java Servlet technology was created as a portable way toprovide dynamic, user-oriented content.

-----------------------------26962244645705

Content-Disposition: form-data; name="upload"

 

上傳

-----------------------------26962244645705--

此處有一個斷行符號符

前面4行和後面6行是表單的一些屬性,是預設加入的。

 

2.出去檔案流中的多餘內容(只支援ie)

UploadServlet2

public class UploadServlet2 extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {String tempFileName = (String) request.getSession().getId();// create the tempfile.File temp = new File("d:/temp", tempFileName);FileOutputStream o = new FileOutputStream(temp);if (request.getContentLength() > 297) {// write theupload content to the temp file.InputStream in = request.getInputStream();byte b[] = new byte[1024];int n;while ((n = in.read(b)) != -1) {o.write(b, 0, n);}o.close();in.close();// read the tempfile.RandomAccessFile random = new RandomAccessFile(temp, "r");// read Line2 tofind the name of the upload file.int second = 1;String secondLine = null;while (second <= 2) {secondLine = random.readLine();second++;}// get the lastlocation of the dir char.'\\'.int position = secondLine.lastIndexOf('\\');// get the nameof the upload file.String fileName = secondLine.substring(position + 1,secondLine.length() - 1);// relocate tothe head of file.random.seek(0);// get thelocation of the char.'Enter' in Line4.long forthEndPosition = 0;int forth = 1;while ((n = random.readByte()) != -1 && (forth <= 4)) {if (n == '\n') {forthEndPosition = random.getFilePointer();forth++;}}File realFile = new File("d:/temp", fileName);RandomAccessFile random2 = new RandomAccessFile(realFile, "rw");// locate the endposition of the content.Count backwards 6 lines.random.seek(random.length());long endPosition = random.getFilePointer();long mark = endPosition;int j = 1;while ((mark >= 0) && (j <= 6)) {mark--;random.seek(mark);n = random.readByte();if (n == '\n') {endPosition = random.getFilePointer();j++;}}// locate to thebegin of content.Count for 4 lines's end position.random.seek(forthEndPosition);long startPoint = random.getFilePointer();// read the realcontent and write it to the realFile.while (startPoint < endPosition - 1) {n = random.readByte();random2.write(n);startPoint = random.getFilePointer();}random2.close();random.close();// delete the tempfile.temp.delete();System.out.println("File uploadsuccess!");} else {System.out.println("Nofile!");}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.