java實現文件上傳FileUpload

》java實現文件上傳FileUpload  作者:左軒、Shiny

FileUploadUtil.java

package com.shiny.ertao.utils;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import com.shiny.ertao.model.GoodsFile;


public class FileUploadUtil {
	//默認文件後綴
	private static String extName=".jpg";
	private static String uploadDir = "goods";
	
	/**
	 * 獲取文件擴展名 如jpg,png,gif,doc,exe,rar==
	 * @param fileName 文件名
	 * @return
	 */
	public static String getFileExt(String fileName){
		
		if(!fileName.contains(".")) return extName;
		if(fileName.endsWith("."))  return extName;
		
		return fileName.substring(fileName.lastIndexOf(".")+1);	
	}
	
	
	
	/**
	 * 替換文件名
	 * @param oldName  文件名
	 * @return 返回一個32位隨機文件名
	 */
	public static String updateFileName(String oldName){
		
		return UUID.randomUUID().toString()+"."+getFileExt(oldName);
	
	}
	
	/**
	 * 返回一個新文件名
	 * @param newName 新文件名(不帶後綴)
	 * @param oldName 舊文件名
	 * @return
	 */
	public static String updateFileName(String newName,String oldName){
		
		return newName+"."+getFileExt(oldName);
	
	}
	
	
	/**
	 * 文件上傳
	 * @param file		文件對象
	 * @param filePath  新文件路徑+文件名(必須存在)
	 * @return
	 */
	public static boolean uploadFile(File file,String fileName){
		boolean flag = false;
		InputStream in=null;
		OutputStream out = null;
		try {
			 in = new FileInputStream(file);
			 out = new FileOutputStream(fileName);
			 byte[] b = new byte[1024];
			 int len=0;
			 while((len=in.read(b))!=-1){
				 out.write(b,0,len); 
			 }
			 flag = true;
			 out.close();
			 in.close();	 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return flag;
	}
	
	/**
	 * 匹配後綴是否支持
	 * @param oldName 文件名
	 * @param exts  後綴數組
	 * @return
	 */
	public static boolean chekcExt(String oldName,String[] exts){
		String ext = getFileExt(oldName);
		boolean flag = false;
		for(int i=0;i<exts.length;i++){
			
			if(ext.equalsIgnoreCase(exts[i])){
				flag = true;
			}	
		}
		
		return flag;	
	}
	
	/**圖片上傳
	 * 獲取拼接後的圖片
	 * @param goodsFile   圖片對象
	 * @param basePath	   上傳路徑
	 * @return
	 */
	public static String getUploadFile(GoodsFile goodsFile,String basePath){
		StringBuffer buff  = new StringBuffer();
	
			
			for(int i=0;i<goodsFile.getGoodsImage().length;i++){
				String temp = goodsFile.getGoodsImageFileName()[i];
				String fileName = FileUploadUtil.updateFileName(temp);
				//System.out.println("新文件名==>"+fileName);
				//組合文件名
				buff.append(fileName+"?");	
				//文件上傳
				FileUploadUtil.uploadFile(goodsFile.getGoodsImage()[i], basePath+"\\"+fileName);

			}
			
		return buff.substring(0,buff.length()-1);
	}
	
	
	
	
	
	

}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章