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

下节用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. Core Data的那点事儿~

    一.介绍下Core Data CoreData在早些年iOS开发中使用不多,因为其本身性能略低,以及不使用SQL语句而失去的灵活性,再加上FMDB之类封装SQLite的三方框架很好用,所以一直不受待见 ...

  2. 【转载】UML图示与代码对照

    一.类继承 public class Father { } public class Child : Father { } 二.接口继承 public interface IBreath { } pu ...

  3. PCB SQL SERVER 发送邮件(异步改同步)

    采用SQL SERVER发送邮件是队列方式(异步)发送邮件,所以在我们执行发送邮件后,无法立即获取到邮件是否发送成功了,而在PCB行业实际应用中是需要立即获取发送邮件是否成功的状态来决定下一步逻辑该如 ...

  4. 基于ASP.Net Core开发一套通用后台框架记录-(项目的搭建)

    写在前面 本系列博客是本人在学习的过程中搭建学习的记录,如果对你有所帮助那再好不过.如果您有发现错误,请告知我,我会第一时间修改. 前期我不会公开源码,我想是一点点敲代码,不然复制.粘贴那就没意思了. ...

  5. webview加载本地页面

    main.xml中布局webview,activity中设置如下 MyWebView=(WebView)findViewById(R.id.webView1); MyWebView.requestFo ...

  6. python网络爬虫数据中的三种数据解析方式

    一.正则解析 常用正则表达式回顾: 单字符: . : 除换行以外所有字符 [] :[aoe] [a-w] 匹配集合中任意一个字符 \d :数字 [0-9] \D : 非数字 \w :数字.字母.下划线 ...

  7. ACM_百度的面试(单调栈)

    百度的面试 Time Limit: 2000/1000ms (Java/Others) Problem Description: 在一个二维平面,从左到右竖立n根高度分别为:a[1],a[2],... ...

  8. 【转】MySQL存储引擎中的MyISAM和InnoDB区别详解

    转自:http://www.jb51.net/article/62457.htm MyISAM是MySQL的默认数据库引擎(5.5版之前),由早期的ISAM(Indexed Sequential Ac ...

  9. 自学Python十二 战斗吧Scrapy!

    初窥Scrapy Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 还是先推荐几个学习的教程:Scrapy 0.2 ...

  10. 小小的IP,大大的耦合,你痛过吗?

    什么是耦合? 耦合,是架构中,本来不相干的代码.模块.服务.系统因为某些原因联系在一起,各自独立性差,影响则相互影响,变动则相互变动的一种架构状态. 感官上,怎么发现系统中的耦合? 作为技术人,每每在 ...