纯净、安全、绿色的下载网站

首页|软件分类|下载排行|最新软件|IT学院

当前位置:首页IT学院IT技术

servlet处理上传文件 使用Servlet处理一个上传的文件

sdr_zd   2021-03-30 我要评论

Servlet中可以使用post请求上传文件使用getReader()和getInputStream()自己处理也可以使用getPart()或getParts()封装了一些功能的方法处理getParts()可以同时上传多个文件。接下来使用四个Demo来练习一下使用方法

一.使用getReader()和getInputStream()

Demo1

<!-- 这是HTML代码块窗体网页上显示的是一个选择文件的input框和一个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 {
  //读取请求Body
  byte[] body = readBody(request);
  //取得所有Body内容的字符串表示
  String textBody = new String(body, "ISO-8859-1");
  //取得上传的文件的文件名(取得路径并分离)
  String filename = getFilename(textBody);
  //取得文件内容在Body中的首尾索引
  Position p = getFilePosition(request, textBody);
  //将内容输出到文件
  writeTo(filename, body, p);
 }
 //存放索引的类
 class Position{
  int begin;
  int end;
  Position(int begin, int end) {
   this.begin = begin;
   this.end = end;
  }
 }
 //读取请求body
 private byte[] readBody(HttpServletRequest request) throws IOException {
  int formDataLength = request.getContentLength();
  //获得ServletInputStream对象
  //getReader()和getInputStream()只能则一调用否则会抛出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="的长度
  //通过后台调试我发现filename=后加的是带着双引号的路径名在获取路径名时不需要分号所以在分离时就将分号也分离掉了
  String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
  //找到文件名这行的末尾过滤掉对于获取文件名而言的无用信息
  filename = filename.substring(0, filename.indexOf("\n"));
  //获取不包含路径名的文件名
  filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.lastIndexOf("\""));
  //此时后台打印分离路径后的文件名并将其作为返回值返回
  System.out.println(filename);
  return filename;
 }
 //取得文件开始和结束位置
 private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
  //取得文件区段边界信息
  String contentType = request.getContentType();
  String boundaryText = contentType.substring(
    contentType.lastIndexOf("=") + 1, contentType.length());
  //取得实际上传文件的起始与结束位置
  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 {
  //默认上传的文件是在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共同使用使用时通过更改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中必须设置@MutipartConfig标注才能使用getPart()相关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对象
  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();
 }
}

这个Demo和第一个代码最大的区别就是通过getPart()方法获得了Part对象通过part对象的getHeader()方法指定标头获得对应的值。

在Tomcat中要在Servlet上设置@MultipartConfig才能取得Part对象否则getPart会得到null

@MultipartConfig含有的属性如下:

  • fileSizeThreshold:整数值设置若上传文件大小超过设置门槛则先写入缓存文件默认值为0
  • location:字符串设置设置写入文件时的目录使用时与write方法一起使用下一个Demo中演示如何使用默认是空字符串
  • maxFileSize:限制上传文件大小默认-1L即无限制
  • maxRequestSize:限制multipart/form-data请求个数默认值为-1L

Demo3

使用Part的write方法进行文件的写入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
//设置属性这里的最后一级不用分隔符可以与Demo2中writeTo方法的路径做一下对比
@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 {
  //文件名中可能有中文字符所以进行编码设置使用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) {}
}

若要实现同时上传多个文件则可以使用getParts()方法获取到的Part对象被保存在一个Collection中

Demo4

<!-- 该HTML是三个input选框选择三个文件 -->
<!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遍历获取每一个Part对象
  for(Part part : request.getParts()) {
   if(part.getName().startsWith("file")) {
    String filename = getFilename(part);
    part.write(filename);
   }
  }
 }
 //与之前的getFilename()方法相同
 private String getFilename(Part part) {
}

总结

以上就是这篇文章的全部内容了希望本文的内容对大家的学习或者工作具有一定的参考学习价值谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接


相关文章

猜您喜欢

网友评论

Copyright 2020 www.Shellfishsoft.com 【贝软下载站】 版权所有 软件发布

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 点此查看联系方式