dou.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.io.*"%> <%@ page import="java.util.*"%> <%@ page import="javax.servlet.*"%> <%@ page import="javax.servlet.http.*"%> <html><head><title>upFile</title></head> <body bgcolor="#ffffff"> <% int MAX_SIZE = 102400 * 102400; String rootPath; DataInputStream in = null; FileOutputStream fileOut = null; String remoteAddr = request.getRemoteAddr(); String serverName = request.getServerName(); String realPath = request.getRealPath(serverName); realPath = realPath.substring(0,realPath.lastIndexOf("\\")); rootPath = realPath + "\\upload\\"; String contentType = request.getContentType(); try{ if(contentType.indexOf("multipart/form-data") >= 0){ in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); if(formDataLength > MAX_SIZE){ out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>"); return; } byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while(totalBytesRead < formDataLength){ byteRead = in.read(dataBytes,totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes,"UTF-8"); String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0,saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); String fileName = rootPath + saveFile; int pos; pos = file.indexOf("filename=\""); pos = file.indexOf("\n",pos) + 1; pos = file.indexOf("\n",pos) + 1; pos = file.indexOf("\n",pos) + 1; int boundaryLocation = file.indexOf(boundary,pos) - 4; int startPos = ((file.substring(0,pos)).getBytes()).length; int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length; File checkFile = new File(fileName); if(checkFile.exists()){ out.println("<p>" + saveFile + "文件已经存在.</p>"); } File fileDir = new File(rootPath); if(!fileDir.exists()){ fileDir.mkdirs(); } fileOut = new FileOutputStream(fileName); fileOut.write(dataBytes,startPos,(endPos - startPos)); fileOut.close(); out.println(saveFile + "文件成功上传.</p>"); out.println("<p>文件大小为"+formDataLength/1024 + "KB.</p>"); }else{ String content = request.getContentType(); out.println("<p>上传的数据类型不是multipart/form-data</p>"); } }catch(Exception ex){ throw new ServletException(ex.getMessage()); } %> </body> </html>
upload.jsp
<%@ page contentType="text/html;charset=UTF-8"%> <html> <title><%= application.getServerInfo() %></title> <body> 上传文件程序应用示例 <form action="dou.jsp" method="post" enctype="multipart/form-data"> <%-- 类型enctype用multipart/form-data,这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传。--%> 请选择要上传的文件<input type="file" name="upfile" size="50"> <input type="submit" value="提交并显示文件大小"> </form> </body> </html>