会报错:java.lang.IndexOutOfBoundsException,我确定是文件结尾索引坐标错了,但不知道为什么,请大虾帮忙看看问题在哪?
1、从request中读出字节:
ServletInputStream stm=request.getInputStream();
int len=request.getContentLength(),
n=0;
byte[] b=new byte[len];
while(n<len)
{
n+=stm.read(b,n,len);
}
stm.close();
2、获取文件起始位置:
String bs=new String(b),
rc=request.getContentType(),
boundary=rc.substring(rc.lastIndexOf("=")+1, rc.length());//分界线文字
String sn=bs.substring(bs.indexOf("filename=\"")+10),
nm=sn.substring(sn.lastIndexOf("\",sn.indexOf("\""))+1, sn.indexOf("\"")),
ex=nm.substring(nm.indexOf(".")+1);//扩展名
int ci=bs.indexOf("Content-Type:");
String type=bs.substring(ci+13, bs.indexOf("\r",ci)).trim();//类型名
////取文件在字节流中的位置索引,加6减4是因为有\r\n\r\n\r\n
int x=bs.substring(0,bs.indexOf("\n",ci)+4).getBytes().length,
y=bs.substring(0,bs.lastIndexOf(boundary)-4).getBytes().length; //结束位置索引y的值太大,导致错误
3、保存文件:
FileOutputStream f=new FileOutputStream(path);
f.write(b,x,y-x);
f.flush();
f.close();