利用apache的FileUpload组件上传文件的时候,刚开始的时候,还没有问题,一些小附件能上传,可是当测试了一个大附件之后,就报了内存溢出,再上传小附件,也上传不了,还是报内存溢出?为何?
    以下是我处理的代码:    DiskFileUpload fileUpload = new DiskFileUpload();
    //设置允许用户上传文件大小,单位:字节
    fileUpload.setSizeMax(500*1024*1024);
    //设置最多允许在内存中存储的数据,单位:字节
    fileUpload.setSizeThreshold(100*1024*1024);
    //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
    //在进行文件上传的时候文件先存再内存中,然后才会存到server上,
    // 但是如果内存放不下那么大的文件
    //就必须用硬盘上的 一个临时文件夹来保存这个文件的部分,然后转存
    //现在默认的文件存储的路径是
    String tempPath = System.getProperty("user.dir");
    tempPath = tempPath.replace('\\','/');
    String temp = tempPath.substring(0, tempPath.length-3) +"webapps/BJRoadMIS/temp";
    fileUpload.setRepositoryPath(temp);
 //获取传入的表单中的参数值
    try {
fileItems = fileUpload.parseRequest(request);
Iterator iterator = fileItems.iterator();
while(iterator.hasNext()){
FileItem fileItem = (FileItem)iterator.next();
if (fileItem.isFormField()){
value = value+segment+fileItem.getString();
}
};
try {
    value = new String(value.getBytes("ISO-8859-1"),"gbk");
} catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}

String[] s = value.split(segment);         if(s.length>1){
uploadPath = tempPath+"/webapps/BJRoadMIS/upload/";

try {
iterator = fileItems.iterator();
while(iterator.hasNext()) {
FileItem fileItem = (FileItem)iterator.next();
//文件域的表单信息
if (!fileItem.isFormField()) {
String strName = fileItem.getName();
uploadFileName = strName.substring(strName.lastIndexOf("\\")+1, strName.length());
long size = fileItem.getSize();
if((strName==null||strName.equals("")) && size==0)
continue; pp=uploadFileName.substring(uploadFileName.lastIndexOf("."),uploadFileName.length()); File savedFile = new File(uploadPath +datelog+pp );
fileItem.write(savedFile);
request.setAttribute("msg","save file successful!");
}
} if(request.getAttribute("msg")== null){
request.setAttribute("msg","save file failed!");
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}