說明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);
}
%>