据说古老了点,所以代码比较繁琐,主要用于处理文件的地方太多。

下节用SERVLET3.0的Part进行操作一下。

form.html:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html ;charset=UTF-8">
</head>
<body>
  <form method="post" action="upload.do" enctype="multipart/form-data">
    file: <input type="file" name="filename" value="" /><br>
    <input type="submit" value="Upload" name="upload" />
  </form>
</body>
</html>

uploadServlet.java:

package cc.openhome;

import java.io.DataInputStream;
import java.io.FileNotFoundException;
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.do")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        byte[] body = readBody(request);
        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;
          Position(int begin, int end) {
            this.begin = begin;
            this.end = end;
          }
    }

    private byte[] readBody(HttpServletRequest request)
            throws IOException{
        int formDataLength = request.getContentLength();
        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 reqBody) {
        String filename = reqBody.substring(
                reqBody.indexOf("filename=\"") + 10);
        filename = filename.substring(0, filename.indexOf("\n"));
        filename = filename.substring(
                filename.lastIndexOf("\\") + 1, filename.indexOf("\""));
        return filename;
    }

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

    }

}

Servlet中使用getInputStream进行文件上传的更多相关文章

  1. 分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载

    摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢) <!--设置文件上传需要的jar--> <dependency> <grou ...

  2. zt对于C#中的FileUpload解决文件上传大小限制的问题设置

    对于C#中的FileUpload解决文件上传大小限制的问题设置 您可能没意识到,但对于可以使用该技术上载的文件的大小存在限制.默认情况下,使用 FileUpload 控件上载到服务器的文件最大为 4M ...

  3. servlet 通过 FileItem 实现多文件上传

    [本文简介] 一个servlet 多文件上传的简单例子. [依赖包] commons-fileupload-1.3.1.jar commons-io-2.2.jar [依赖包下载] commons-f ...

  4. springboot中使用分页,文件上传,jquery的具体步骤(持续更新)

    分页: pom.xml     加依赖 <dependency> <groupId>com.github.pagehelper</groupId> <arti ...

  5. Spring中使用StandardServletMultipartResolver进行文件上传

    从Spring3.1开始,Spring提供了两个MultipartResolver的实现用于处理multipart请求,分别是:CommonsMultipartResolver和StandardSer ...

  6. SpringMVC中使用CommonsMultipartResolver进行文件上传

    概述: CommonsMultipartResolver是基于Apache的Commons FileUpload来实现文件上传功能的.所以在项目中需要相应的jar文件. FileUpload版本要求1 ...

  7. 2020最新Servlet+form表单实现文件上传(图片)

    servlet实现文件上传接受 这几天学了一点文件上传,有很多不会,在网查了许多博客,但是最新的没有,都比较久了 因为我是小白,版本更新了,以前的方法自己费了好久才弄懂,写个随笔方便以后查找 代码奉上 ...

  8. java中io流实现文件上传下载

    新建io.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" page ...

  9. JAVA中使用FTPClient实现文件上传下载实例代码

    一.上传文件 原理就不介绍了,大家直接看代码吧 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ...

随机推荐

  1. 使用Keras做OCR时报错:ValueError: Tensor Tensor is not an element of this graph

    现象 项目使用 Flask + Keras + Tensorflow 同样的代码在机器A和B上都能正常运行,但在机器C上就会报如下异常.机器A和B的环境是先安装的,运行.调试成功后才尝试在C上跑. F ...

  2. Vue 页面回退参数被当作字符串处理

    当时情景是这样的,我从A页面跳到B页面时会传一个Boolean类型的参数,当B跳到C,再从C返回B的时候,控制台打印发现参数还在,可是判断怎么都不起作用,后来发现,当页面返回的时候,默认将参数变成了字 ...

  3. 【洛谷4219】[BJOI2014]大融合(线段树分治)

    题目: 洛谷4219 分析: 很明显,查询的是删掉某条边后两端点所在连通块大小的乘积. 有加边和删边,想到LCT.但是我不会用LCT查连通块大小啊.果断弃了 有加边和删边,还跟连通性有关,于是开始yy ...

  4. UNIX环境高级编程--5

    标准I/O库流和FILE对象:    所有I/O函数都是围绕文件描述符的.当打开一个文件时,即返回一个文件描述符,然后该文件描述符就用于后续的I/O操作.当用标准I/O库打开或者创建一个文件时,我们已 ...

  5. 前端-Node.js思维导图笔记

    看不清的朋友右键保存或者新窗口打开哦!喜欢我可以关注我,还有更多前端思维导图笔记

  6. <form> 标签

    <form method="传送方式" action="服务器文件"> action :浏览者输入的数据被传送到的地方,比如一个PHP页面(save ...

  7. JS——undefined、null

    1.undefined == false   //返回false 2.null == false     //返回false 3.undefined == null    //返回true 4.und ...

  8. CAD实现自定义实体夹点移动(com接口VB语言)

    主要用到函数说明: MxDrawXCustomEvent::MxDrawXCustomEntity::moveGripPointsAt 自定义实体事件,自定义实体夹点被移动,详细说明如下: 参数 说明 ...

  9. .net 学习视频

    http://www.iqiyi.com/a_19rrh9jx9p.html http://www.cnblogs.com/aarond/p/SQLDispatcher.html  --读写分离 ht ...

  10. 新手入门学习angular.js的心得体会

    看了一天的angular.js,只要记住这是关于双向数据绑定 和单向数据绑定就可以,看看开发文档,短时间内还是可以直接入手的,看个人理解能力(我是小白). 这几天开始着手学习angularjs的有关知 ...