会报错: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();
为什么要用ISO-8859-1?
UTF-8不行吗?
//用ISO-8859-1
public class file {
/*
//public void upload(HttpServletRequest q,String path,String nm) throws IOException
public void upload(HttpServletRequest q,String path) throws IOException
{
//多文件上传
byte[] b=this.getBytes(q);
this.put(q,b,path);
//this.toFile(b,fp,finfo);//移入put主要是为了避免多次循环
// this.getString(fp);
}
/*
info[] fa=null;
String ec="ISO-8859-1",
bs=new String(b,ec),
rc=q.getContentType(),
boundary=rc.substring(rc.lastIndexOf("=")+1, rc.length()),//分界线文字
l = "\r\n", //换行符
pf = "--";
//各参数之间分隔符为:"--" + boundary
String[] fs=bs.split(pf+boundary);
int len=fs.length;
System.out.println("fs.length:"+len+boundary);
//StringBuilder sb=new StringBuilder("\nfs:\n");
if(len>2){
fa=new info[len-2];
for(int i=1;i<len-1;i++)//String f :fs
{
String f=fs[i];
int ns=f.indexOf("filename=\"");
if(ns>0)
{
//System.out.println(f);
String sn=f.substring(ns+10),
nm=sn.substring(sn.lastIndexOf("\",sn.indexOf("\""))+1, sn.indexOf("\"")),//filename返回值有可能是全路径,如IE
ex=nm.substring(nm.indexOf(".")+1);//扩展名
int ci=f.indexOf("Content-Type:"),
bi=f.indexOf("\n",ci)+1;
bi=f.indexOf("\n",bi)+1;
String type=f.substring(ci+13, f.indexOf("\r",ci)).trim();//类型名
//取文件在字节流中的位置索引,加4减2是因为有换行符
int x=f.substring(0,bi).getBytes(ec).length,//x位置错误(bs.length()-st.length())+
y=f.getBytes(ec).length-2;//y的值超出了b.lenth上传图片报错:java.lang.IndexOutOfBoundsException
this.toFile(f.getBytes(ec),path+nm,new info(x,y,type,nm,ex));
}
}
}
//return fa;
}
/*
//3、保存从字节流到文件
FileOutputStream f=new FileOutputStream(path);
//f.write(b);
//f.write(b);
try{
f.write(b,o.x,o.y-o.x);
}
finally{
f.flush();
f.close();
}
}