页面只有2个上传的input 我只上传一张图片的时候是没问题的,在我本机的file目录下图片可以正常打开并且可以预览。
但是我同时上传2张图片的时候虽然上传成功了file目录下有2张图片,但是打开后都无法预览。
代码如下:
@Override
public String execute() throws Exception {
String tempname = "";//文件临时名称
String filedate = "";//文件日期(用于文件名称)
byte[] b = new byte[1024];
int len; 
System.out.println(title);
System.out.println("文件名称=="+myFileFileName);
System.out.println("文件类型=="+myFileContentType);

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yymmddhhmmss");
for(int i =0;i<myFile.size();i++){
InputStream is = new FileInputStream(myFile.get(i));//获取上传文件
System.out.println("(i)myFile=="+myFile.get(i));
String path = ServletActionContext.getRequest().getRealPath("/file");
tempname = path+"\\"+sdf.format(date)+myFileFileName.get(i);
if(tempname.endsWith(".jpg")||tempname.endsWith(".bmp")){
imgPath = tempname;
System.out.println("图片路径="+imgPath);
}else{
videoPath = tempname;
System.out.println("视频路径="+videoPath);
}
if(imgPath!=null && !imgPath.equals("")){
OutputStream os = new FileOutputStream(imgPath);//IO操作文件复制到指定目录
while((len = is.read(b))!=-1){
os.write(b,0,len);
}
System.out.println("11bbb="+b+"len--"+len);
System.out.println("第一次-close");
os.close();
len=0;
}
if(videoPath!=null && !videoPath.equals("")){
OutputStream os2 = new FileOutputStream(videoPath);
int lens;
while((lens=is.read(b))!=-1){
os2.write(b,0,lens);
}
os2.close();
}
is.close();
}这是代码。如果我只上传一个图片是没有问题的。
可如果我上传2张就有问题了,我打印了每次获取的路径都正确,File对象也正确。认为是inputstream的错但说不出那里有错,希望有知道的可以帮帮小妹,虚心求教。

解决方案 »

  1.   

    问题解决了。放到同一个输出流里写入文件即可。因为之前为了方便保存路径做了判断在使用不同的输出流。其实没必要。看下面代码String tempname = "";//文件临时名称
    String filedate = "";//文件日期(用于文件名称)
    byte[] b = new byte[1024];
    int len; 
    System.out.println(title);
    System.out.println("文件名称=="+myFileFileName);
    System.out.println("文件类型=="+myFileContentType);

    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yymmddhhmmss");
    for(int i =0;i<myFile.size();i++){
    InputStream is = new FileInputStream(myFile.get(i));//获取上传文件
    System.out.println("(i)myFile=="+myFile.get(i));
    String path = ServletActionContext.getRequest().getRealPath("/file");
    tempname = path+"\\"+sdf.format(date)+myFileFileName.get(i);
    if(tempname.endsWith(".jpg")||tempname.endsWith(".bmp")){
    imgPath = tempname;
    System.out.println("图片路径="+imgPath);
    }else{
    videoPath = tempname;
    System.out.println("视频路径="+videoPath);
    }
    OutputStream os = new FileOutputStream(tempname);//IO操作文件复制到指定目录
    while((len = is.read(b))!=-1){
    os.write(b,0,len);
    }
    os.close();
    is.close();
    }还是只能靠自己啊。