e哥 2016-09-30 06:58 采纳率: 0%
浏览 966

上传文本文件没问题,图片文件报错

会报错: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();

  • 写回答

2条回答 默认 最新

  • e哥 2016-10-03 09:17
    关注

    为什么要用ISO-8859-1?
    UTF-8不行吗?

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?