java中数据上传

public void doUpload(HttpServletRequest req)throws ServletException, IOException
{
byte[] line=new byte[128];
ServletInputStream in=req.getInputStream();//获得上传文件
int i=in.readLine(line,0,128);
/*
Reads the input stream, one line at a time. Starting at an offset,
reads bytes into an array, until it reads a certain number of bytes or reaches a newline character,
which it reads into the array as well. This method returns -1 if it reaches the end of the input
stream before reading the maximum number of bytes.
return :integer specifying the actual number of bytes read,
*/

if(i<3)
return;

int boundaryLength=i-2;
String boundary=new String(line,0,boundaryLength);
fields=new Hashtable();
while(i!=-1)
{
String newLine=new String(line,0,i);
if(newLine.startsWith("Content-Dispostion:form-data;name=\""));
{
if(newLine.indexOf("filename=\"")!=-1)//Returns the index within this string of the first occurrence of the specified substring.

{
setFilename(new String(line,0,i-2));//调用方法取出文件名
if(filename==null)
return;
i=in.readLine(line,0,128);
setContentType(new String(line,0,i-2));//调用方法
i=in.readLine(line,0,128);

i=in.readLine(line,0,128);
newLine=new String(line,0,i);

PrintWriter pw=new PrintWriter(new BufferedWriter(
new FileWriter((savePath==null? " ": savePath) +filename)));

//文件的最后一行包含换行符,因此必须检查当前行是否是最后一行
while(i!=-1 && !newLine.startsWith(boundary))
{
i=in.readLine(line,0,128);
if((i==boundaryLength+2 || i==boundaryLength+4)&&
(new String(line,0,i).startsWith(boundary)))
pw.print(newLine.substring(0,newLine.length()-2));
else
pw.print(newLine);
newLine=new String(line,0,i);
}
pw.close();
}
else
{
int pos=newLine.indexOf("name=\"");
String fieldName=newLine.substring(pos+6,newLine.length()-3);
i=in.readLine(line,0,128);
i=in.readLine(line,0,128);
newLine=new String(line,0,i);
StringBuffer fieldValue=new StringBuffer(128);
while(i!=-1&&!newLine.startsWith(boundary))
{
i=in.readLine(line,0,128);
if((i==boundaryLength+2 || i==boundaryLength+4)&&
(new String(line,0,i).startsWith(boundary)))
fieldValue.append(newLine.substring(0,newLine.length()-2));
else
fieldValue.append(newLine);
newLine=new String(line,0,i);
}
fields.put(fieldName,fieldValue.toString());
}
}
i=in.readLine(line,0,128);

}

}用这种方法获得的数据,再打开的时候总是显示文件已被损坏,不能正常的打开是什么原因呀?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值