Servlet实现文件上传的三种方法总结

Servlet实现文件上传的三种方法总结

1. 通过getInputStream()取得上传文件。

/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.individuals.web.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; 

/**
 *
 * @author Barudisshu
 */
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet { 

  /**
   * Processes requests for both HTTP
   * <code>GET</code> and
   * <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //读取请求Body
    byte[] body = readBody(request);
    //取得所有Body内容的字符串表示
    String textBody = new String(body, "ISO-8859-1");
    //取得上传的文件名称
    String fileName = getFileName(textBody);
    //取得文件开始与结束位置
    Position p = getFilePosition(request, textBody);
    //输出至文件
    writeTo(fileName, body, p);
  } 

  //构造类
  class Position { 

    int begin;
    int end; 

    public Position(int begin, int end) {
      this.begin = begin;
      this.end = end;
    }
  } 

  private byte[] readBody(HttpServletRequest request) throws IOException {
    //获取请求文本字节长度
    int formDataLength = request.getContentLength();
    //取得ServletInputStream输入流对象
    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 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 String getFileName(String requestBody) {
    String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
    fileName = fileName.substring(0, fileName.indexOf("\n"));
    fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\"")); 

    return fileName;
  } 

  private void writeTo(String fileName, byte[] body, Position p) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName);
    fileOutputStream.write(body, p.begin, (p.end - p.begin));
    fileOutputStream.flush();
    fileOutputStream.close();
  } 

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Handles the HTTP
   * <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>
}

 2. 通过getPart()、getParts()取得上传文件。

body格式:

POST http://www.example.com HTTP/1.1
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA  

------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"  

title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png  

PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--  

[html] view plain copy
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.individuals.web.servlet; 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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; 

/**
 *
 * @author Barudisshu
 */
@MultipartConfig
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet { 

  /**
   * Processes requests for both HTTP
   * <code>GET</code> and
   * <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    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("\"")); 

    return fileName;
  } 

  //存储文件
  private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException {
    InputStream in = part.getInputStream();
    OutputStream out = new FileOutputStream("e:/workspace/" + fileName);
    byte[] buffer = new byte[1024];
    int length = -1;
    while ((length = in.read(buffer)) != -1) {
      out.write(buffer, 0, length);
    } 

    in.close();
    out.close();
  } 

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Handles the HTTP
   * <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }
}

3、另一种较为简单的方法:采用part的wirte(String fileName)上传,浏览器将产生临时TMP文件

/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.individuals.web.servlet; 

import java.io.IOException;
import java.io.PrintWriter;
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; 

/**
 *采用part的wirte(String fileName)上传,浏览器将产生临时TMP文件。
 * @author Barudisshu
 */
@MultipartConfig(location = "e:/workspace")
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet { 

  /**
   * Processes requests for both HTTP
   * <code>GET</code> and
   * <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //处理中文文件名
    request.setCharacterEncoding("UTF-8");
    Part part = request.getPart("photo");
    String fileName = getFileName(part);
    //将文件写入location指定的目录
    part.write(fileName);
  } 

  private String getFileName(Part part) {
    String header = part.getHeader("Content-Disposition");
    String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
    return fileName;
  } 

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Handles the HTTP
   * <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  } 

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>
}

以上就是Servlet实现文件上传的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • SpringMVC + servlet3.0 文件上传的配置和实现代码

    简单几步,实现SpringMVC+servlet3.0文件上传功能: 第一步:配置web.xml文件中的servlet,添加multipart-config: <!-- SpringMVC --> <servlet> <servlet-name>myWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-clas

  • Android中发送Http请求(包括文件上传、servlet接收)的实例代码

    复制代码 代码如下: /*** 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件* @param actionUrl 上传路径 * @param params 请求参数 key为参数名,value为参数值 * @param file 上传文件 */public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {try {PostMethod p

  • Servlet3.0实现文件上传的方法

    Servlet 实现文件上传 所谓文件上传就是将本地的文件发送到服务器中保存.例如我们向百度网盘中上传本地的资源或者我们将写好的博客上传到服务器等等就是典型的文件上传. Servlet 3.0 上次完成文件下载功能使用的是 Servlet 2.5,但是想要完成文件上传,那么继续使用 Servlet 2.5 肯定不是一个好的选择,因此我们使用 Servlet 3.0 来完成文件上传.下面我来简单介绍一下 Servlet 3.0 的新特性: 1.新增的注解支持 该版本新增了若干注解,用于简化 Ser

  • java基于servlet实现文件上传功能解析

    最近项目需要做一个文件上传功能,做完了分享下,顺带当做笔记. 上传功能用后台用java实现,前端主要是js的ajax实现.后台还加入定时删除临时文件. 效果如图 首先是上传功能的主要类,下面是代码 package util.upload; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterat

  • java基于servlet使用组件smartUpload实现文件上传

    文件上传在web应用中是非常常见的,现在我就介绍下基于servlet的文件上传,基于Struts2的文件上传可以看: 页面端代码: <%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <ht

  • servlet+jquery实现文件上传进度条示例代码

    现在文件的上传,特别是大文件上传,都需要进度条,让客户知道上传进度. 本文简单记录下如何弄进度条,以及一些上传信息,比如文件的大小,上传速度,预计剩余时间等一些相关信息.代码是匆忙下简单写的,一些验证没做,或代码存在一些隐患,不严谨的地方.本文代码只供参考. 进度条的样式多种多样,有些网站弄得非常绚烂漂亮.本文UI端不太懂,只会一些简单的基本的css而已,所以进度条弄得不好看.本文侧重的给读者提供一个参考,一个实现思路而已. 注:由于jQuery版本用的是2.1.1,所以如果跑本例子源码,请用I

  • servlet+JSP+mysql实现文件上传的方法

    本文实例讲述了servlet+JSP+mysql实现文件上传的方法.分享给大家供大家参考,具体如下: 一.文件上传的基本操作: 1. 表单属性enctype的设置 multipart/form-data和application/x-www-form-urlencoded的区别 FORM元素的enctype属性指定了表单数据向服务器提交时所采用的编码类型,默认的缺省值是"application/x-www-form-urlencoded". 然而,在向服务器发送大量的文本.包含非ASCI

  • Servlet实现多文件上传功能

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip : 点击打开链接 2) commons-io-2.3-bin.zip :  点击打开链接 接着把这两个jar包放到 lib文件夹下: 二.文件上传的表单提交方式必须是POST方式 编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded 比如:<fo

  • Java Servlet简单实例分享(文件上传下载demo)

    项目结构 src com servletdemo DownloadServlet.java ShowServlet.java UploadServlet.java WebContent jsp servlet download.html fileupload.jsp input.jsp WEB-INF lib commons-fileupload-1.3.1.jar commons-io-2.4.jar 1.简单实例 ShowServlet.java package com.servletdem

  • Servlet实现文件上传,可多文件上传示例

    一.Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip:  点击打开链接 2)  commons-io-2.3-bin.zip:    点击打开链接 接着把这两个jar包放到 lib文件夹下: 二:文件上传的表单提交方式必须是POST方式, 编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded 比如: &l

随机推荐