⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filetransfer.java

📁 javaBB,一套很不錯的JSP源碼,特共享給大家
💻 JAVA
字号:
package org.javabb.infra;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.javabb.vo.PostFile;

import sun.misc.ExtensionInstallationException;

import com.opensymphony.webwork.dispatcher.multipart.MultiPartRequestWrapper;

/**
 * @author Dalton Camargo 
 */
public class FileTransfer {

    /**
     * Classe para enviar upload atrav閟 de uma action
     * Exemplo de utiliza玢o atrav閟 da Action:
     *		
     *		String nameFile = "arquivo_" + editorial2.getIdEditorial();
     *					
     *		MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
     *		String arquivo = FileTransfer.verificaUpload(multiWrapper,nameFile);
     *		if(arquivo != null && !arquivo.equals("")){
     *			arquivo = "/diretorio/Uploads/" + nameFile + "." + arquivo;
     *		}			
     *		
     *		editorial2.setImage(arquivo);
     * 
     * @param multiWrapper - 
     * @param inputNameFile - Nome do arquivo a ser gravado no F.System
     * @return - Nomes dos arquivos enviados
     */
    public static ArrayList uploadFile(MultiPartRequestWrapper multiWrapper) {
		String fileName = "";
		ArrayList filesExt = new ArrayList();
		
		if (multiWrapper.hasErrors()) {
			Collection errors = multiWrapper.getErrors();
			Iterator i = errors.iterator();
			while (i.hasNext()) {
				//obj.addActionError((String) i.next());
			}
		} else {
			Enumeration e = multiWrapper.getFileNames();
			while (e.hasMoreElements()) {
				
				String inputValue = (String) e.nextElement();
				
				String contentType = multiWrapper.getContentType(inputValue);
				
				if(contentType != null) {
					fileName = multiWrapper.getFilesystemName(inputValue);
					
					File file = multiWrapper.getFile(inputValue);
	
					String nameFile = file.getName();
					String pathFile = file.getAbsolutePath().replaceAll(nameFile, "");

					String nameWithoutDot = nameFile.substring(0, nameFile.indexOf('.'));
					
					String extension = "";
					int whereDot = nameFile.lastIndexOf( '.' );
					if ( 0 < whereDot && whereDot <= nameFile .length()-2 ){
					   extension = nameFile.substring(whereDot+1 );
					}
					String inputNameFile = new String(Double.toString(System.currentTimeMillis()));
					
					file.renameTo(new File(pathFile + nameWithoutDot + "-" + inputNameFile + "." + extension));
					filesExt.add(nameWithoutDot + "-" + inputNameFile + "." + extension);
				} else {
					//N鉶 foi selecionado nenhum arquivo
					filesExt.add(null);
				}
				
			}
		}
		return filesExt;
    }

    
    public static HashMap uploadFileRecursive(MultiPartRequestWrapper multiWrapper) throws Exception {
    	return uploadFileRecursive(multiWrapper, null, false);
    }
    
    /**
     * Class to send files through an WebWork's action
     * @param multiWrapper - 
     * @param inputNameFile - Nome do arquivo a ser gravado no F.System
     * @return - HashMap contendo como chave o nome do arquivo 
     * enviado, e como valor o tamanho do arquivo
     */
	public static HashMap uploadFileRecursive(
			MultiPartRequestWrapper multiWrapper, String inputFileName,
			boolean isAvatar) throws Exception {

		HashMap filesExt = new HashMap();
		
		if (multiWrapper.hasErrors()) {
			//Collection errors = multiWrapper.getErrors();
			//Iterator i = errors.iterator();
			/*while (i.hasNext()) {
				obj.addActionError((String) i.next());
			}*/
		} else {
			Enumeration e = multiWrapper.getFileNames();
			while (e.hasMoreElements()) {
				
				String inputValue = (String) e.nextElement();
				
				String contentType = multiWrapper.getContentType(inputValue);
				
				if(contentType != null) {
					String fileName = multiWrapper.getFilesystemName(inputValue);
					
					File file = multiWrapper.getFile(inputValue);
	
					String nameFile = file.getName();
					String pathFile = file.getAbsolutePath().replaceAll(nameFile, "");
					String nameWithoutDot = nameFile.substring(0, nameFile.indexOf('.'));
					
					String extension = "";
					int whereDot = nameFile.lastIndexOf( '.' );
					if ( 0 < whereDot && whereDot <= nameFile .length()-2 ){
					   extension = nameFile.substring(whereDot+1 );
					}

					if(isAvatar){
						//Just JPG and GIF are alloweds
						if(!"jpg".equalsIgnoreCase(extension) && !"gif".equalsIgnoreCase(extension)){
							deleteFile(pathFile, nameFile);
							throw new ExtensionInstallationException("Only JPG and GIF are allowed!");
						}
					}
					
					if("exe".equals(extension) ||  "scr".equals(extension) || "cmd".equals(extension)){
						deleteFile(pathFile, nameFile);
						throw new ExtensionInstallationException("This kind of extension is not allowed!");
					}
					
					String createdFileName = new String(Double.toString(
							System.currentTimeMillis())).replaceAll("\\.", "0");

					//Aways returns the file lenght in KB
					//long fileLenght = (file.length()>=1024)?(file.length()/1024):(1024/file.length());
					
					//Modified just to return the file in KB or Bytes
					String fileLenghtReturn = "";
					if(file.length()>=1024){
						fileLenghtReturn = (file.length()/1024) + " KB";
					} else{
						fileLenghtReturn = file.length() + " bytes";
					}

					String newFileName = null;
					if(inputFileName != null && !"".equals(inputFileName)) {
						deleteFile(pathFile, inputFileName);
						newFileName = inputFileName;
					} else {
						newFileName = createdFileName + "-" + nameWithoutDot + "." + extension;
						newFileName = newFileName.replaceAll(" ", "_");
					}
					file.renameTo(new File(pathFile + newFileName));
					filesExt.put(newFileName, fileLenghtReturn);
					
				}
			}
		}
		return filesExt;
    }
   
    
    /**
     * @param multiWrapper
     * @return
     */
    public static String getAbsolutPathName(MultiPartRequestWrapper multiWrapper){
    	String pathFile = "";
    	Enumeration e = multiWrapper.getFileNames();
		while (e.hasMoreElements()) {
			
			String inputValue = (String) e.nextElement();
			
			String contentType = multiWrapper.getContentType(inputValue);
			
			if(contentType != null) {
				String fileName = multiWrapper.getFilesystemName(inputValue);
				
				File file = multiWrapper.getFile(inputValue);

				String nameFile = file.getName();
				pathFile = file.getAbsolutePath().replaceAll(nameFile, "");
				break;
			}
		}
		return pathFile;
    }
    
    public static boolean deleteFile(String path, String fileName){
    	return new File(path + fileName).delete();
    }

    public static void deleteFileByList(Set set){
    	if(set != null && set.size() > 0){
    		Iterator it =  set.iterator();
    		while (it.hasNext()) {
    			PostFile pFile = (PostFile)it.next();
    			deleteFile(pFile.getFilePath(), pFile.getFileName());
    	      }
    	}
    }
    
	public static List uploadFiles(HttpServletRequest req, String inputFileName,
			boolean isAvatar) throws Exception {

		MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper)req;
		HashMap hm = FileTransfer.uploadFileRecursive(multiWrapper, inputFileName, isAvatar);
		List files = new ArrayList();
		String pathName = FileTransfer.getAbsolutPathName((MultiPartRequestWrapper)req);
		Iterator i = hm.keySet().iterator();
		while (i.hasNext()) {
			String fileName = (String) i.next();
			String fileSize = hm.get(fileName).toString();
			PostFile pFile = new PostFile();
			pFile.setFileName(fileName);
			pFile.setFileSize(fileSize);
			pFile.setFilePath(pathName);
			files.add(pFile);
		}

		return files;
	}
    
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -