fileuploadhelper.java

来自「利用hibernate框架进行开发的全景浏览与导航系统。」· Java 代码 · 共 90 行

JAVA
90
字号
package com.shandong.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import org.apache.struts.upload.FormFile;

public class FileUploadHelper {

	static public List getAllowedTypes(String filePath) {
		List allowedTypes = new LinkedList();
		allowedTypes.add("video/x-ms-wmv");
		allowedTypes.add("rmvb");
		allowedTypes.add("rm");
		String value = PropertyHelper.getConfigProperty(filePath,
				"mpeg_allowed");
		if ("true".equals(value)) {
			allowedTypes.add("mpeg");
			allowedTypes.add("mpg");
		}
		value = PropertyHelper.getConfigProperty(filePath, "avi_allowed");
		if ("true".equals(value)) {
			allowedTypes.add("avi");
		}
		return allowedTypes;
	}

	static public String getExtension(String fileName) {
		int dotPos = fileName.lastIndexOf(".");
		if (dotPos == -1) {
			return null;
		}
		return fileName.substring(dotPos + 1);
	}

	static public String saveFile(FormFile file, String realPath) {
		try {
			InputStream in = file.getInputStream();

			File newFile = File.createTempFile("Video_", "."
					+ getExtension(file.getFileName()), new File(realPath));
			OutputStream out = new FileOutputStream(newFile);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
				out.write(buffer, 0, bytesRead);
			}
			in.close();
			out.close();
			return newFile.getName();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	static public boolean deleteFile(String oldFile, String realPath) {
		try {
			File delFile = new File(realPath + File.separator + oldFile);

			delFile.delete();

			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	static public String rewriteFile(String oldFile, FormFile file,
			String realPath) {
		try {
			deleteFile(oldFile, realPath);

			return saveFile(file, realPath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}

⌨️ 快捷键说明

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