jsp-文件的上传(转).
该程序的主要代码,我引用网友的,并做了一些改进.上这个帖子的原因之一,是为了修正之前自己的一些误解.
概述:
一些网友,包括我,也曾经试图通过 input type 为 file的控件,获取其文件的完整路径.后来我发现行不通,这也许是web设计者的事,本来这个控件就是用来上传用的,所以,在前端,可以通过 input type='file'的控件将待上传的文件包装起来,然后通过请求,以流的形式将请求发送给服务器端,然后服务器端通过获取请求对应的流进行处理,然后往服务器端写文件.
一下是源码:
首先上贴客户端代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <html> 2 <head> 3 <title>前台-接收文件</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 </head> 6 <body> 7 <form name="frm" method="post" action="handleFile.jsp" 8 ENCTYPE="multipart/form-data"> 9 <input type="file" name="filept"> 10 <br /> 11 <br /> 12 <input type="submit" name="submit" value="上传"> 13 </form> 14 </body> 15 </html>
然后定义一个'上传文件类' - JspFileUpload,用来上传从客户端发送的文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package spt.uploader; 2 3 import java.io.BufferedOutputStream; 4 import java.io.File; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.text.SimpleDateFormat; 8 import java.util.ArrayList; 9 import java.util.Date; 10 import java.util.Hashtable; 11 import javax.servlet.ServletInputStream; 12 import javax.servlet.http.HttpServletRequest; 13 14 15 /**JSP上传文件类 16 * @author Administrator 17 *2015-1-3 18 */ 19 public class JspFileUpload { 20 /** request对象 */ 21 private HttpServletRequest request = null; 22 /** 上传文件的路径 */ 23 private String uploadPath = null; 24 /** 每次读取得字节的大小 */ 25 private static int BUFSIZE = 1024 * 8; 26 /** 存储参数的Hashtable */ 27 private Hashtable paramHt = new Hashtable(); 28 /** 存储上传的文件的文件名的ArrayList */ 29 private ArrayList updFileArr = new ArrayList(); 30 31 /** 32 * 设定request对象. 33 * 34 * @param request 35 * HttpServletRequest request对象. 36 */ 37 public void setRequest(HttpServletRequest request) { 38 this.request = request; 39 } 40 41 /** 42 * 设定文件上传路径。 43 * 44 * @param path 45 * 用户指定的文件的上传路径。 46 */ 47 public void setUploadPath(String path) { 48 this.uploadPath = path; 49 } 50 51 /** 52 * 文件上传处理主程序。 53 * 54 * @return int 操作结果 0 文件操作成功;1 request对象不存在。 2 没有设定文件保存路径或者文件保存路径不正确;3 55 * 没有设定正确的enctype;4 文件操作异常。 56 */ 57 public int process() { 58 int status = 0; 59 // 文件上传前,对request对象,上传路径以及enctype进行check. 60 status = preCheck(); 61 // 出错的时候返回错误代码. 62 if (status != 0) 63 return status; 64 try { 65 // 参数或者文件名 66 String name = null; 67 // 参数的value 68 String value = null; 69 // 读取的流是否为文件的标志位 70 boolean fileFlag = false; 71 // 要存储的文件。 72 File tmpFile = null; 73 // 上传的文件的名字 74 String fName = null; 75 FileOutputStream baos = null; 76 BufferedOutputStream bos = null; 77 //存储参数的Hashtable 78 paramHt = new Hashtable(); 79 updFileArr = new ArrayList(); 80 int rtnPos = 0; 81 byte[] buffs = new byte[BUFSIZE * 8]; 82 //取得ContentType 83 String contentType = request.getContentType(); 84 int index = contentType.indexOf("boundary="); 85 String boundary = "--" + contentType.substring(index + 9); 86 String endBoundary = boundary + "--"; 87 //从request对象中取得流。 88 ServletInputStream sis = request.getInputStream(); 89 // 读取1行 90 while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) { 91 String strBuff = new String(buffs, 0, rtnPos); 92 // 读取1行数据. 93 if (strBuff.startsWith(boundary)) { 94 if (name != null && name.trim().length() > 0) { 95 if (fileFlag) { 96 bos.flush(); 97 baos.close(); 98 bos.close(); 99 baos = null; 100 bos = null; 101 updFileArr.add(fName); 102 } else { 103 Object obj = paramHt.get(name); 104 ArrayList al = new ArrayList(); 105 if (obj != null) { 106 al = (ArrayList) obj; 107 } 108 al.add(value); 109 System.out.println(value); 110 paramHt.put(name, al); 111 } 112 } 113 name = new String(); 114 value = new String(); 115 fileFlag = false; 116 fName = new String(); 117 rtnPos = sis.readLine(buffs, 0, buffs.length); 118 if (rtnPos != -1) { 119 strBuff = new String(buffs, 0, rtnPos); 120 if (strBuff.toLowerCase().startsWith("content-disposition: form-data; ")) { 121 int nIndex = strBuff.toLowerCase().indexOf("name=\""); 122 int nLastIndex = strBuff.toLowerCase().indexOf("\"", nIndex + 6); 123 name = strBuff.substring(nIndex + 6, nLastIndex); 124 } 125 int fIndex = strBuff.toLowerCase().indexOf("filename=\""); 126 if (fIndex != -1) { 127 fileFlag = true; 128 int fLastIndex = strBuff.toLowerCase().indexOf("\"", fIndex + 10); 129 fName = strBuff.substring(fIndex + 10, fLastIndex); 130 fName = getFileName(fName); 131 if (fName == null || fName.trim().length() == 0) { 132 fileFlag = false; 133 sis.readLine(buffs, 0, buffs.length); 134 sis.readLine(buffs, 0, buffs.length); 135 sis.readLine(buffs, 0, buffs.length); 136 continue; 137 } else { 138 fName = getFileNameByTime(fName); 139 sis.readLine(buffs, 0, buffs.length); 140 sis.readLine(buffs, 0, buffs.length); 141 } 142 } 143 } 144 } else if (strBuff.startsWith(endBoundary)) { 145 if (name != null && name.trim().length() > 0) { 146 if (fileFlag) { 147 bos.flush(); 148 baos.close(); 149 bos.close(); 150 baos = null; 151 bos = null; 152 updFileArr.add(fName); 153 } else { 154 Object obj = paramHt.get(name); 155 ArrayList al = new ArrayList(); 156 if (obj != null) { 157 al = (ArrayList) obj; 158 } 159 al.add(value); 160 paramHt.put(name, al); 161 } 162 } 163 } else { 164 if (fileFlag) { 165 if (baos == null && bos == null) { 166 tmpFile = new File(uploadPath + fName); 167 baos = new FileOutputStream(tmpFile); 168 bos = new BufferedOutputStream(baos); 169 } 170 bos.write(buffs, 0, rtnPos); 171 baos.flush(); 172 } else { 173 System.out.println("test :" + value + "--" + strBuff); 174 value = value + strBuff; 175 } 176 } 177 } 178 } catch (IOException e) { 179 status = 4; 180 } 181 return status; 182 } 183 184 private int preCheck() { 185 int errCode = 0; 186 if (request == null) //不存在请求. 187 return 1; 188 if (uploadPath == null || uploadPath.trim().length() == 0) //上传文件路径错误. 189 return 2; 190 else { 191 File tmpF = new File(uploadPath); 192 if (!tmpF.exists()) 193 return 2; 194 } 195 String contentType = request.getContentType(); 196 if (contentType.indexOf("multipart/form-data") == -1) 197 return 3; 198 return errCode; 199 } 200 201 public String getParameter(String name) { 202 String value = ""; 203 if (name == null || name.trim().length() == 0) 204 return value; 205 value = (paramHt.get(name) == null) ? "" : (String) ((ArrayList) paramHt.get(name)).get(0); 206 return value; 207 } 208 209 public String[] getParameters(String name) { 210 if (name == null || name.trim().length() == 0) 211 return null; 212 if (paramHt.get(name) == null) 213 return null; 214 ArrayList al = (ArrayList) paramHt.get(name); 215 String[] strArr = new String[al.size()]; 216 for (int i = 0; i < al.size(); i++) 217 strArr[i] = (String) al.get(i); 218 return strArr; 219 } 220 221 public int getUpdFileSize() { 222 return updFileArr.size(); 223 } 224 225 public String[] getUpdFileNames() { 226 String[] strArr = new String[updFileArr.size()]; 227 for (int i = 0; i < updFileArr.size(); i++) 228 strArr[i] = (String) updFileArr.get(i); 229 return strArr; 230 } 231 232 private String getFileName(String input) { 233 int fIndex = input.lastIndexOf("\\"); 234 if (fIndex == -1) { 235 fIndex = input.lastIndexOf("/"); 236 if (fIndex == -1) { 237 return input; 238 } 239 } 240 input = input.substring(fIndex + 1); 241 return input; 242 } 243 244 private String getFileNameByTime(String input) { 245 int index = input.indexOf("."); 246 Date dt = new Date(); 247 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 248 return input.substring(0, index) + sdf.format(dt) + input.substring(index); 249 } 250 }
最后定义一个.jsp文件,用来调用'上传文件类',并处理文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ page contentType="text/html; charset=utf-8"%> 2 <%@ page import="spt.uploader.JspFileUpload"%> 3 4 <html> 5 <head> 6 <title>后台-jsp-处理前端上传的文件.</title> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 8 </head> 9 <body> 10 <% 11 //初始化 12 JspFileUpload jfu = new JspFileUpload(); 13 //设定request对象 14 jfu.setRequest(request); 15 //设定上传文件的目标路径 16 jfu.setUploadPath("C:\\"); 17 //上传处理 18 jfu.process(); 19 //取得上传的文件的名字 20 String[] fileArr = jfu.getUpdFileNames(); 21 //取得上传文件的个数 22 int fileNumber = jfu.getUpdFileSize(); 23 //下面的是测试输出的代码。 24 out.println("fileArr size:" + fileArr.length); 25 if (fileArr.length > 0) 26 out.println("fileArr 0:" + fileArr[0]); 27 %> 28 </body> 29 </html>