struts2上傳多張圖片的方法
阿新 • • 發佈:2019-01-03
原文地址
package eao; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.servlet.ServletContext; import org.apache.struts2.ServletActionContext; import util.PictureNameBuilder; public class PictureEAO { public static String[] savePicture(File[] pictures,String[] pictureFilename,String savePath){ //開一個和檔案陣列大小相同的字串陣列 String[] imgsrc=new String[pictures.length]; //獲取專案上下文 ServletContext context=ServletActionContext.getServletContext(); //獲取照片儲存的相對地址在專案中應對應的全路徑 String realSavePath=context.getRealPath(savePath); //建立資料夾 File saveDirectory=new File(realSavePath); if(!saveDirectory.exists()){saveDirectory.mkdirs();} //處理圖片 for(int i=0;i<imgsrc.length;i++){ //獲取第i張圖片的上傳時的名稱 String photoFileName=pictureFilename[i]; //獲取第i張圖片儲存時的名稱 String saveFileName=PictureNameBuilder.getPictureName(); //取檔案字尾 String ext=photoFileName.substring(photoFileName.lastIndexOf(".")); //拼接得到檔案的專案中儲存地址 String outFilePath=realSavePath+"/"+saveFileName+ext; //儲存專案圖片的相對地址,方便在網頁中進行訪問 imgsrc[i]=savePath+"/"+saveFileName+ext; System.out.println("%%%%%%%%%%%%%%%%%%%%%%%% 截斷前"+imgsrc[i]+"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); imgsrc[i]=imgsrc[i].substring(1); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%% 截斷後"+imgsrc[i]+"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); try { //開緩衝檔案輸入流,並將pictures[i]作為檔案輸入流傳入 BufferedInputStream bis=new BufferedInputStream(new FileInputStream(pictures[i])); //開緩衝檔案輸出流,並將outFilePath作為檔案輸出地址 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(outFilePath)); int tmp=-1; //按為寫入輸出流 while ((tmp=bis.read())!=-1){ bos.write(tmp); } //將輸出流中的內容寫入檔案 bos.flush(); //關閉兩個流 bos.close(); bis.close(); } catch (Exception e) { e.printStackTrace(); } } return imgsrc; } }