iT邦幫忙

DAY 14
4

JSP 學習分享系列 第 14

JSP 如何上傳檔案

說明JSP 如何上傳檔案和一些技巧
1.先寫一個上傳的小畫面
=== uploadFile.jsp ===

	<%@page contentType="text/html" pageEncoding="UTF-8"%>

  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Uplaod File Sample</title>
  
  
    <form action="recvFile.jsp" method="post" enctype="application/x-www-form-urlencoded">
      Select File to upload :<input type="file" name="filename" value="" /><br>
      <input type="submit" value="Upload" name="upload" />
    </form>
  

2.再寫一個處理接上傳的jsp
主要是request.getInputStream() 這個把所有的資料都接回來
=== recvFile.jsp ===

	<%@page import="java.io.*"%>
<%@page import="java.util.*" %>
<%
  try{
    ServletInputStream in = request.getInputStream();
    int bLen=0;
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while((bLen=in.read(buffer))>0){
      baos.write(buffer, 0, bLen);
    }
    String rs = baos.toString();

    int a = rs.indexOf("\r\n");
    int b = rs.indexOf("\r\n",a+1);

    String boundary = rs.substring(0,a);
    int bdlen = boundary.length();
    //get the last location byte
    int sec = rs.indexOf(boundary, bdlen);
    //get the content-Disposition
    int cdlen = rs.indexOf("Content-Disposition",bdlen);
    int cdlenl = rs.indexOf("\r\n",cdlen);
    String cdstr = rs.substring(cdlen+20,cdlenl);
    int ctlen = rs.indexOf("Content-Type",bdlen);
    int ctlenl = rs.indexOf("\r\n",ctlen);
    String ctstr = rs.substring(ctlen +13,ctlenl );
    String name = "";
    int fnlen = cdstr.indexOf("filename=");
    int fnlenl = cdstr.indexOf("\"",fnlen+10);
    name = cdstr.substring(fnlen+10,fnlenl);

    String filename = "d:/kill/"+name;
    FileOutputStream fos = new FileOutputStream(filename);
    fos.write(baos.toByteArray());
    fos.close();
    pageContext.forward("uploadFile.jsp");
  }catch(Exception ex){
    System.out.println(ex);
  }
%>

上一篇
JSP 和 Hibernate 的設定教學第四篇
下一篇
JSP and JavaMail part1
系列文
JSP 學習分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言