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

}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值