`

单文件上传

 
阅读更多
Action操作类



public class Action extends BaseAction{
	// 附件信息
	private File iconFilepath; // 文件对像
	private String iconFilepathFileName; // 文件名
	private String iconFilepathContentType; // 文件的minitype

	
	/**
	 * 保存
	 *
	 * @return
	 */
	public String save() {
		if (log.isDebugEnabled()) {
			log.debug("上传的文件名为:" + this.iconFilepathFileName);
			log.debug("上传的文件minitype为:" + this.iconFilepathContentType);
		}
		try {
			String attachemnt = "";
			if (StringUtils.isNotBlank(iconFilepathFileName)) {
				// 上传新附件
				attachemnt = this.uploadClientAttach();
			}

			if (log.isDebugEnabled()) {
				log.debug("附件上传后保存的服务器端相对路径为:" + attachemnt);
			}
			if (StringUtils.isNotBlank(attachemnt)) {
                             //Action操作
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	
	/**
	 * 上传图片
	 * 
	 * @return
	 * @throws IOException
	 * @throws CallerException
	 */
	private String uploadClientAttach() throws IOException {
		String filePath = "upload/temp";
		String serviceFilePath = FileUtil.uploadFile(iconFilepath, iconFilepathFileName, filePath);
		return serviceFilePath;
	}

	
	public File getIconFilepath() {
		return iconFilepath;
	}

	public void setIconFilepath(File iconFilepath) {
		this.iconFilepath = iconFilepath;
	}

	public String getIconFilepathFileName() {
		return iconFilepathFileName;
	}

	public void setIconFilepathFileName(String iconFilepathFileName) {
		this.iconFilepathFileName = iconFilepathFileName;
	}

	public String getIconFilepathContentType() {
		return iconFilepathContentType;
	}

	public void setIconFilepathContentType(String iconFilepathContentType) {
		this.iconFilepathContentType = iconFilepathContentType;
	}
}

Jsp页面
<form id="adForm" name="adForm" action="save.do" method="post" enctype="multipart/form-data">
					<tr>
						<th width="20%"><span class="cRed">*</span>图片:</th>
						<td colspan="3">
							<input type="file" id="iconFilepath" name="iconFilepath" /><span id="tip" class="cRed"></span>
							<s:if test="iconPath != ''&&iconPath != null">
								<br/><img alt="图片预览" src="<s:url value='/'/><s:property value='iconPath'/>" width="500px">
							</s:if>
						</td>
					</tr>
					
				</tbody>
			</table>
		</form>

文件操作工具类
package cn.site.framework.util.file;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.etuo.site.framework.exception.HackathonException;
import cn.etuo.site.framework.util.ConfigManager;
import cn.etuo.site.framework.util.Constants;
import cn.etuo.site.framework.util.DateUtil;
import cn.etuo.site.framework.util.RespType;

/**
 * 
 * 文件操作工具类
 * <p/>
 * 
 * @author [url=mailto:holin@huijisoft.com]Holin Ding[/url]
 * @version Date: 2012-12-5 上午11:04:33
 * @serial 1.0
 * @since 2012-12-5 上午11:04:33
 */
public class FileUtil {
	/**
	 * 返回文件的高度和宽度
	 * 
	 * @param file
	 *            要计算宽高的文件
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Integer> getImageHAndW(File file) throws IOException {
		Map<String, Integer> map = new HashMap();
		BufferedImage bi = javax.imageio.ImageIO.read(file);
		int flag = 0;
		if (bi != null) {
			flag = 1;
			map.put("width", bi.getWidth());
			map.put("height", bi.getHeight());
		} else {
			flag = 2;
		}
		map.put("flag", flag);
		return map;
	}

	/**
	 * 验证文件的长宽是否符合要求
	 * 
	 * @param map
	 *            调用FileUtil.getImageHAndW()方法返回的map
	 * @param width
	 *            宽度限制
	 * @param height
	 *            高度限制
	 * @param type
	 *            验证类型 0:图片的长宽 是否等于传过来的长宽 ;1:图片的长宽在传过来的长宽范围内
	 * @return 1:不符合要求 2:符合要求
	 */
	public static int checkImageHAndW(Map<String, Integer> map, int width, int height, int type) {
		int returnValue = 0;
		int flag = map.get("flag");
		int imageWidth = map.get("width");
		int imageHeight = map.get("height");
		if (type == 0) {
			if (imageWidth == width && imageHeight == height) {
				returnValue = 2;
			} else {
				returnValue = 1;
			}
		} else if (type == 1) {
			if (imageWidth <= width && width <= height) {
				returnValue = 2;
			} else {
				returnValue = 1;
			}
		}
		return returnValue;
	}

	/**
	 * 检查文件的后缀名是否符合要求
	 * 
	 * @param fileName
	 *            要检查的文件
	 * @param types
	 *            符合要求的后缀:例:jpg,png,gif
	 * @return 符合要求:true;不符合要求:false;
	 */
	public static boolean checkFileType(String fileName, String types) {
		String name = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		name = name.toLowerCase();
		types = types.toLowerCase();
		if (types.contains(name)) {
			return true;
		}
		return false;
	}

	/**
	 * 在工程目录下创建文件夹
	 * 
	 * @param fileFolderName
	 *            文件夹名称
	 * @return
	 */
	public static File creatFolder(String fileFolderName) {
		// 定义保存的路径,取当前项目的绝对路径
		String savepath = ServletActionContext.getServletContext().getRealPath("/");
		// 根据路径创建文件路径对象
		File file = new File(savepath + "/" + fileFolderName);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	/**
	 * 上传文件操作,
	 * 
	 * @param file
	 *            要上传的文件
	 * @param fileName
	 *            上传的文件的文件名
	 * @param filePath
	 *            上传到服务器的位置
	 * @return 上传后的文件在服务器中保存的相对路径
	 * @throws IOException
	 */
	public static String uploadFile(File file, String fileName, String filePath) throws IOException {
		// 保存到服务器上的文件名
		String destFileName = "";
		// 保存到服务器上的路径及文件名
		String serviceFilePath = "";
		// 创建上传目标文件夹 按年月日格式生成文件夹
		String fileFolderName = filePath + "/" + DateUtil.getSeqDate();
		File folder = FileUtil.creatFolder(fileFolderName);
		if (file != null) {
			destFileName = FileUtil.uploadFile(folder, file, fileName, Constants.UPLOAD_FILE_NAME_TYPE_DATE);
			serviceFilePath = fileFolderName + "/" + destFileName;
		}
		return serviceFilePath;
	}

	/**
	 * 将file生成物理文件上传到指定的目录中
	 * 
	 * @param folder
	 *            文件要写的路径(调用FileUtil.creatFolder 方法得到的file对象)
	 * @param upload
	 *            要生成的物理文件
	 * @param uploadFileName
	 *            原文件名
	 * @param type
	 *            类型 1:用原文件名生成物理文件;2:用HHmmssSSS时间格式作为文件名生成物理文件(可扩展)
	 * @return 返回上传后的文件路径
	 * @throws IOException
	 */
	public static String uploadFile(File folder, File upload, String uploadFileName, int type) throws IOException {
		String fileName = "";
		switch (type) {
		case 1:
			fileName = uploadFileName;
			break;
		case 2:
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("HHmmssSSS");

			fileName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1, uploadFileName.length());
			fileName = df.format(date) + "." + fileName;
			break;
		}

		File f = new File(folder, fileName);
		// 如果上传的文件是一个空文件,即0字节的文件,则创建一个空文件到磁盘中
		if (upload.length() <= 0) {
			f.createNewFile();
		} else {
			FileUtils.copyFile(upload, f);
		}
		return fileName;
	}

	/**
	 * 从文件服务器中删除指定的文件
	 * 
	 * @param fileName
	 *            要删除的文件名及路径的全称
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteFile(String fileName) throws IOException {
		// 定义保存的路径,取当前项目的绝对路径
		String savepath = ServletActionContext.getServletContext().getRealPath("/");

		File file = new File(savepath + "/" + fileName);
		return file.delete();
	}

	/**
	 * 验证上传图片的分辨率是否符合要求
	 * 
	 * @param file
	 *            要验证的文件
	 * @param zooms
	 *            存放分辨率宽高的数组, zooms[0]:存放宽度 zooms[1]:存放高度
	 * @param type
	 *            是否支持等比缩放 0:支持等比缩放, 1:不支持等比缩放
	 * @return true可以上传、false 不可以上传
	 * @throws IOException
	 */
	public static boolean checkZoom(File file, String[] zooms, int type) throws IOException {
		Map<String, Integer> map = getImageHAndW(file);
		double imageWidth = map.get("width");
		double imageHeight = map.get("height");

		double zoomWidth = Integer.valueOf(zooms[0]);// 设置的宽
		double zoomHight = Integer.valueOf(zooms[1]);// 设置的高
		if (type == 0) {
			if ((imageWidth / imageHeight) == (zoomWidth / zoomHight)) {
				return true;
			} else {
				return false;
			}
		} else {
			int returnFlag = checkImageHAndW(map, (int) zoomWidth, (int) zoomHight, 0);
			if (returnFlag == 2) {
				return true;
			} else {
				return false;
			}
		}
	}

	/**
	 * 检查上传文件的大小
	 * 
	 * @param f
	 *            要上传的文件
	 * @param maxSize
	 *            文件大小上限,单位M
	 * @return 返回值true表示验证文件大小通过<br/>
	 *         返回值false表示验证文件大小不通过,或者File为null<br/>
	 */
	public static boolean checkFileMaxSize(File f, int maxSize) {
		boolean re = false;
		if (f == null) {
			return re;
		}
		long max = maxSize * 1048576; // 将maxSize转换成字节单位
		long fileSize = f.length(); // 获得文件大小
		if (fileSize > max) {
			re = false;
		} else {
			re = true;
		}
		/*
		 * try { FileInputStream fis = new FileInputStream(f); long fileSize =
		 * fis.available() / 1024;
		 * 
		 * } catch (IOException e) { e.printStackTrace(); }
		 */
		return re;
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile2(String sPath) {
		boolean flag = false;

		return flag;
	}

	/**
	 * 删除目录(文件夹)以及目录下的文件
	 * 
	 * @param sPath
	 *            被删除目录的文件路径
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String sPath) throws Exception {
		// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在,或者不是一个目录,则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				File file = new File(files[i].getAbsolutePath());
				// 路径为文件且不为空则进行删除
				if (file.isFile() && file.exists()) {
					file.delete();
					flag = true;
				}
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 读取文件内容
	 * 
	 * @param file
	 *            要读取的文件
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws IOException
	 */
	public static String readFile(File file) {
		StringBuffer sb = new StringBuffer("");
		try {
			InputStreamReader fl = new InputStreamReader(new FileInputStream(file), "UTF-8");
			BufferedReader bf = new BufferedReader(fl);
			String context = null;
			do {
				context = bf.readLine();
				if (context == null) {
					break;
				} else if (!context.equals("")) {
					sb.append(context + "\n");
				}
			} while (context != null);
			bf.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return sb.toString();
	}

	/**
	 * <br>
	 * 拷贝文件
	 * 
	 * @param input
	 *            文件的原始路径
	 * @param output
	 *            文件的目的路径
	 * 
	 * @return boolean
	 * 
	 * @throws IOException
	 */
	public static boolean copy(String input, String output) throws Exception {
		File fromFile;
		File toFile;
		fromFile = new File(input);

		if (!fromFile.exists()) {
			return false;
		}
		toFile = new File(output);
		if (toFile.exists()) {
			return true;
		}

		FileInputStream fis = null;

		FileOutputStream fos = null;

		try {
			create(output);

			fis = new FileInputStream(fromFile);

			fos = new FileOutputStream(toFile);

			int bytesRead;

			byte[] buf = new byte[4 * 1024]; // 4K buffer

			while ((bytesRead = fis.read(buf)) != -1) {
				fos.write(buf, 0, bytesRead);
			}

			fos.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(fos);
			IOUtils.closeQuietly(fis);
		}

		return true;
	}

	/**
	 * <br>
	 * 创建新文件
	 * 
	 * @param name
	 *            需要创建的文件的全路径
	 * 
	 * @return boolean
	 */
	public static boolean create(String name) throws Exception {

		File f = new File(name);

		if (f.exists()) {
			return true;
		}

		String path = StringUtils.substringBeforeLast(name, File.separator);
		createDir(path);

		File file = new File(name);

		try {
			file.createNewFile();
		} catch (IOException e) {
			throw e;
		}
		return true;
	}

	/**
	 * <br>
	 * 创建目录
	 * 
	 * @param path
	 *            要创建目录的位置
	 * 
	 * <br>
	 *            如果文件已存在,则返回
	 * 
	 * @return boolean
	 */
	public static boolean createDir(String path) {
		File filepath = new File(path);
		if (!filepath.exists()) {
			return filepath.mkdirs();
		}
		return true;
	}
}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics