Servlet中使用getInputStream进行文件上传

简介:

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

下节用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();
        
    }

}
复制代码
目录
相关文章
|
Java 开发者
Servlet 教程 之 Servlet 文件上传 1
Servlet 文件上传教程展示了如何利用 HTML 表单和 Servlet 处理文件上传。关键点包括:POST 方法的 form,enctype 设为 &quot;multipart/form-data&quot;,以及 action 指向如 UploadServlet 的处理程序。所需的 jar 包有 commons-fileupload-1.3.2 和 commons-io-2.5.jar。Servlet 3.0 已内置文件上传支持,无需额外组件。示例的 upload.jsp 文件包含一个单文件上传表单,使用 input[type=&quot;file&quot;] 元素。
205 5
|
XML 数据格式
Servlet 教程 之 Servlet 文件上传 3
该教程介绍了如何使用Servlet进行文件上传。在web.xml中配置了Servlet `UploadServlet`,类为`com.baidu.test.UploadServlet`,映射路径为`/TomcatTest/UploadServlet`。用户需通过创建的HTML表单提交文件,访问URL为:http://localhost:8080/TomcatTest/upload.jsp。
151 0
|
Java
java servlet 文件上传 req.getPart null 返回空值
java servlet 文件上传 req.getPart null 返回空值
303 0
|
缓存 前端开发 Java
15:Servlet 3.0文件上传与下载-Java Web
15:Servlet 3.0文件上传与下载-Java Web
487 5
|
存储 Java Apache
Servlet 教程 之 Servlet 文件上传 2
该教程介绍了如何使用Servlet进行文件上传。关键步骤包括:确保引入Apache Commons FileUpload和IO库,创建`UploadServlet`,设置上传配置,解析请求以提取文件数据,并将文件保存至服务器指定目录。如果上传成功,用户将被重定向到`message.jsp`显示提示信息。
275 1
|
Java Apache
基于servlet完成文件上传功能
基于servlet完成文件上传功能
166 0
|
移动开发 前端开发 JavaScript
Spring MVC-09循序渐进之文件上传(基于Servlet3.0+Html5客户端上传文件)
Spring MVC-09循序渐进之文件上传(基于Servlet3.0+Html5客户端上传文件)
150 0
|
前端开发 Java Apache
Spring MVC-09循序渐进之文件上传(基于Servlet3.0+内置功能)
Spring MVC-09循序渐进之文件上传(基于Servlet3.0+内置功能)
185 0
|
XML 应用服务中间件 Linux
Springmvc文件上传(servlet3.0)/下载(ssm)以及坑点
(补充:再linux服务器上可能没用创建文件的权限,那就需要找到文件夹给权限,比如我的chmod -R 777 /home/tomcat/apache-tomcat-default/webapps/food)
290 0
|
Java Spring API
SpringMVC文件上传对Servlet3的支持
SpringMVC内置了对文件上传的支持,它需要我们配置一个MultipartResolver,Servlet3之前它只有一个基于commons-fileupload的实现CommonsMultipartResolver,笔者以前也写过一篇基于CommonsMultipartResolver的文件上传的博文,地址是http://elim.iteye.com/blog/1188116。
1818 0