原文网址:http://blog.163.com/wkyuyang_001/blog/static/10802122820092944334989/
Struts文件上传
1.创建一个工程:
创建一个JSP页面内容如下:
<body>
<form action="uploadAction.do" method="post" enctype="multipart/form-data" >
<input type="file" name="file">
<input type="submit">
</form>
</body>
2.创建一个FormBean继承ActionForm
其中有个private FormFile file ;属性。FormFile类的全名为:org.apache.struts.upload.FormFile
3.创建一个UploadAction继承自Action
然后重写Action的execute()方法:
代码如下:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UploadForm uploadForm = (UploadForm) form;
if(uploadForm.getFile()!=null)
FileUtil.uploadFile(uploadForm.getFile(), "e:/abc/accp");
return null;
}
4.创建FileUtil工具类,里面实现上传的文件的方法:
关键代码如下:
public class FileUtil
{
/*** 创建空白文件
* @param fileName 文件名
* @param dir 保存文件的目录
* @return
*/
private static File createNewFile(String fileName,String dir)
{
File dirs = new File(dir);
//看文件夹是否存在,如果不存在新建目录
if(!dirs.exists())
dirs.mkdirs();
//拼凑文件完成路径
File file = new File(dir+File.separator+fileName);
try {
//判断是否有同名名字,如果有同名文件加随机数改变文件名
while(file.exists()){
int ran = getRandomNumber();
String prefix = getFileNamePrefix( fileName);
String suffix = getFileNameSuffix( fileName);
String name = prefix+ran+"."+suffix;
file = new File(dir+File.separator+name);
}
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/**
* 获得随机数
* @return
*/
private static int getRandomNumber() {
Random random = new Random(new Date().getTime());
return Math.abs(random.nextInt());
}
/**
* 分割文件名 如a.txt 返回 a
* @param fileName
* @return
*/
private static String getFileNamePrefix(String fileName){
int dot = fileName.lastIndexOf(".");
return fileName.substring(0,dot);
}
/**
* 获得文件后缀
* @param fileName
* @return
*/
private static String getFileNameSuffix(String fileName) {
int dot = fileName.lastIndexOf(".");
return fileName.substring(dot+1);
}
/**
* 上传文件
* @param file
* @param dir
* @return
*/
public static String uploadFile(FormFile file,String dir)
{
//获得文件名
String fileName = file.getFileName();
InputStream in = null;
OutputStream out = null;
try
{
in = new BufferedInputStream(file.getInputStream());//构造输入流
File f = createNewFile(fileName,dir);
out = new BufferedOutputStream(new FileOutputStream(f));//构造文件输出流
byte[] buffered = new byte[8192];//读入缓存
int size =0;//一次读到的真实大小
while((size=in.read(buffered,0,8192))!=-1)
{
out.write(buffered,0,size);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
if(in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(out != null) out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}