package com.struts2.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
/*
*
* IT
* 唐智波
* 2010-12-03
* 文件上传辅助类
*
*/
public class FileUpload {
private static final int BUFFER_SIZE = 16 * 1024; //上传的文件大小在16M以下
/**
* 执行Copy File 操作
* @param src 源文件
* @param dst 新路径文件
*/
private static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件的后缀名(.*)
* @param fileName 文件
* @return 后缀
*/
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
/**
* 上传文件
* @param img 文件
* @param imgName 该文件的名字(取得后缀用)
* @param ServerTemp 上传的目的地(文件夹)
* @return
*/
public static String Copy(File img,String imgName,String ServerTemp) {
String imageFileName = new Date().getTime() + getExtention(imgName); //毫秒数.* eg: 123456464.jpg
File imageFile = new File(ServerTemp+ "/" + imageFileName); //再加上 毫秒数的文件名
copy(img, imageFile); //Copy^-ing...!
return imageFileName; //返回上传成功的新文件名(不包括ImgCard文件夹名)
}
}