欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Servlet處理一個(gè)上傳的文件

 更新時(shí)間:2019年01月04日 11:05:21   作者:sdr_zd  
今天小編就為大家分享一篇關(guān)于使用Servlet處理一個(gè)上傳的文件,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧

Servlet中可以使用post請(qǐng)求上傳文件,使用getReader()和getInputStream()自己處理,也可以使用getPart()或getParts()封裝了一些功能的方法處理,getParts()可以同時(shí)上傳多個(gè)文件。接下來(lái)使用四個(gè)Demo來(lái)練習(xí)一下使用方法

一.使用getReader()和getInputStream()

Demo1

<!-- 這是HTML代碼塊,窗體網(wǎng)頁(yè)上顯示的是一個(gè)選擇文件的input框和一個(gè)upload的button -->
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title></title>
 </head>
 <body>
  <form action="upload" method="post" enctype="multipart/form-data">
  選擇文件:<input type="file" name="filename" value="" /><br>
  <input type="submit" value="Upload" name="upload" />
  </form>
 </body>
</html>
//這是Servlet處理部分
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Servlet implementation class uploadServlet
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //讀取請(qǐng)求Body
  byte[] body = readBody(request);
  //取得所有Body內(nèi)容的字符串表示
  String textBody = new String(body, "ISO-8859-1");
  //取得上傳的文件的文件名(取得路徑并分離)
  String filename = getFilename(textBody);
  //取得文件內(nèi)容在Body中的首尾索引
  Position p = getFilePosition(request, textBody);
  //將內(nèi)容輸出到文件
  writeTo(filename, body, p);
 }
 //存放索引的類
 class Position{
  int begin;
  int end;
  Position(int begin, int end) {
   this.begin = begin;
   this.end = end;
  }
 }
 //讀取請(qǐng)求body
 private byte[] readBody(HttpServletRequest request) throws IOException {
  int formDataLength = request.getContentLength();
  //獲得ServletInputStream對(duì)象
  //getReader()和getInputStream()只能則一調(diào)用,否則會(huì)拋出IllegalStateException異常
  DataInputStream dataStream = new DataInputStream(request.getInputStream());
  byte[] body = new byte[formDataLength];
  int totalBytes = 0;
  while(totalBytes < formDataLength) {
   int bytes = dataStream.read(body, totalBytes, formDataLength);
   totalBytes += bytes;
  }
  return body;
 }
 //取得上傳文件名稱
 private String getFilename(String reqBody) {
  //獲取filename的value,10是filename="的長(zhǎng)度
  //通過(guò)后臺(tái)調(diào)試我發(fā)現(xiàn)filename=后加的是帶著雙引號(hào)的路徑名,在獲取路徑名時(shí)不需要分號(hào)所以在分離時(shí)就將分號(hào)也分離掉了
  String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
  //找到文件名這行的末尾,過(guò)濾掉對(duì)于獲取文件名而言的無(wú)用信息
  filename = filename.substring(0, filename.indexOf("\n"));
  //獲取不包含路徑名的文件名
  filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.lastIndexOf("\""));
  //此時(shí)后臺(tái)打印分離路徑后的文件名并將其作為返回值返回
  System.out.println(filename);
  return filename;
 }
 //取得文件開(kāi)始和結(jié)束位置
 private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
  //取得文件區(qū)段邊界信息
  String contentType = request.getContentType();
  String boundaryText = contentType.substring(
    contentType.lastIndexOf("=") + 1, contentType.length());
  //取得實(shí)際上傳文件的起始與結(jié)束位置
  int pos = textBody.indexOf("filename=\"");
  pos = textBody.indexOf("\n", pos) + 1;
  pos = textBody.indexOf("\n", pos) + 1;
  pos = textBody.indexOf("\n", pos) + 1;
  int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
  int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
  int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;
  return new Position(begin, end);
 }
 //輸出至文件
 private void writeTo(String filename, byte[] body, Position p) throws IOException {
  //默認(rèn)上傳的文件是在F:\\javaeeAroundFiles目錄下
  FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename);
  fos.write(body, p.begin, (p.end - p.begin));
  fos.flush();
  fos.close();
 }
}

二.使用getPart()和getInputStream()

Demo2

//HTML代碼塊
<!-- 該HTML供uploadPartDemo和uploadPartDemo2共同使用,使用時(shí)通過(guò)更改body的form的action屬性值控制 -->
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title></title>
 </head>
 <body>
  <form action="uploadPhoto" method="post"
  enctype="multipart/form-data">
  上傳相片:<input type="file" name="photo" /><br><br>
  <input type="submit" value="上傳" name="upload" />
  </form>
 </body>
</html>
//uploadPhotoDemo.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartDemo
//Tomcat中必須設(shè)置@MutipartConfig標(biāo)注才能使用getPart()相關(guān)API
@MultipartConfig
@WebServlet("/uploadPhoto")
public class uploadPartDemo extends HttpServlet {
 private static final long serialVersionUID = 1L;
 //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  //getPart()獲取Part對(duì)象
  Part part = request.getPart("photo");
  String filename = getFilename(part);
  writeTo(filename, part);
 }
 private String getFilename(Part part) {
  String header = part.getHeader("Content-Disposition");
  //獲取完整路徑
  String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
  //filename after substring is: F:\Entertainment\pictures\e5e893df874df44d99f06bc52504a65c.jpg
  System.out.println("filename after substring is: " + filename);
  //獲取文件名
  filename = filename.substring(filename.lastIndexOf("\\") + 1);
  //filename after 2 substring is: e5e893df874df44d99f06bc52504a65c.jpg
  System.out.println("filename after 2 substring is: " + filename);
  return filename;
 }
 private void writeTo(String filename, Part part) throws IOException, FileNotFoundException {
  InputStream is = part.getInputStream();
  FileOutputStream fos = new FileOutputStream("F:\\javaeeAroundFiles\\later\\" + filename);
  byte[] buffer = new byte[1024];
  int length = -1;
  while((length = is.read(buffer)) != -1) {
   fos.write(buffer, 0, length);
  }
  is.close();
  fos.close();
 }
}

這個(gè)Demo和第一個(gè)代碼最大的區(qū)別就是,通過(guò)getPart()方法獲得了Part對(duì)象,通過(guò)part對(duì)象的getHeader()方法指定標(biāo)頭獲得對(duì)應(yīng)的值。

在Tomcat中要在Servlet上設(shè)置@MultipartConfig才能取得Part對(duì)象,否則getPart會(huì)得到null

@MultipartConfig含有的屬性如下:

  • fileSizeThreshold:整數(shù)值設(shè)置,若上傳文件大小超過(guò)設(shè)置門檻,則先寫入緩存文件,默認(rèn)值為0
  • location:字符串設(shè)置,設(shè)置寫入文件時(shí)的目錄,使用時(shí)與write方法一起使用,下一個(gè)Demo中演示如何使用,默認(rèn)是空字符串
  • maxFileSize:限制上傳文件大小,默認(rèn)-1L即無(wú)限制
  • maxRequestSize:限制multipart/form-data請(qǐng)求個(gè)數(shù),默認(rèn)值為-1L

Demo3

使用Part的write方法進(jìn)行文件的寫入,HTML文件查看Demo2注釋部分

//uploadPhotoDemo2.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartDemo2
//設(shè)置屬性,這里的最后一級(jí)不用分隔符,可以與Demo2中writeTo方法的路徑做一下對(duì)比
@MultipartConfig(location="F:\\javaeeAroundFiles\\later")
@WebServlet("/uploadPhoto2")
public class uploadPartDemo2 extends HttpServlet {
 private static final long serialVersionUID = 1L;
 //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //文件名中可能有中文字符所以進(jìn)行編碼設(shè)置,使用setCharacterEncoding()方法
  request.setCharacterEncoding("UTF-8");
  Part part = request.getPart("photo");
  String filename = getFilename(part);
  //使用Part的write方法,寫入location指定路徑
  part.write(filename);
 }
 //獲取文件名與Demo2相同不放代碼
 private String getFilename(Part part) {}
}

若要實(shí)現(xiàn)同時(shí)上傳多個(gè)文件則可以使用getParts()方法,獲取到的Part對(duì)象被保存在一個(gè)Collection中

Demo4

<!-- 該HTML是三個(gè)input選框,選擇三個(gè)文件 -->
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type"
    content="text/html; charset=UTF-8">
  <title></title>
 </head>
 <body>
  <form action="uploadParts" method="post"
   enctype="multipart/form-data">
   文件1:<input type="file" name="file1" value="" /><br>
   文件2:<input type="file" name="file2" value="" /><br>
   文件3:<input type="file" name="file3" value="" /><br><br>
   <input type="submit" value="上傳" name="upload" />
  </form>
 </body>
</html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
//Servlet implementation class uploadPartsDemo
@MultipartConfig(location="F:\\javaeeAroundFiles\\later")
@WebServlet("/uploadParts")
public class uploadPartsDemo extends HttpServlet {
 private static final long serialVersionUID = 1L;
 //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  //使用foreach遍歷獲取每一個(gè)Part對(duì)象
  for(Part part : request.getParts()) {
   if(part.getName().startsWith("file")) {
    String filename = getFilename(part);
    part.write(filename);
   }
  }
 }
 //與之前的getFilename()方法相同
 private String getFilename(Part part) {
}

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

相關(guān)文章

最新評(píng)論