单文件上传笔记
一、文件上传工具类(获取文件.后缀、设置文件名称、保存文件)
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Random;
import org.apache.commons.io.FileUtils;
public class UpDownLoadFile
{
public String saveFile(File file,String fileName,String fileContenType,String realPath) throws IOException
{
String realFileName=getFileName(fileName);
/*System.out.println("realpath: "+realPath);
System.out.println("fileContenType: "+fileContenType);
System.out.println("fileName: "+realFileName);*/
if(file!=null)
{
File saveFile=new File(new File(realPath),realFileName);
if (!saveFile.getParentFile().exists())
saveFile.getParentFile().mkdirs();
FileUtils.copyFile(file, saveFile);//struts2自带文件工具类
}
return realFileName;
}
public String getFileName(String fileName)
{
String result="";
GregorianCalendar cal=new GregorianCalendar();
SimpleDateFormat formatDate=new SimpleDateFormat("yyyyMMddHHmmss");
String strDate=formatDate.format(cal.getTime());//获取日期
//随机数代码
Random random = new Random();
StringBuilder strBuilder=new StringBuilder();
String temp="";
for(int i=0;i<4;i++)
{
temp=String.valueOf(random.nextInt(10));
strBuilder.append(temp);//获取随机数
}
//获取.后缀代码
int dot=fileName.lastIndexOf(".");
String extName=fileName.substring(dot);//获取.后缀
result=strDate+strBuilder+extName;
return result;
}
}
二、web页面
<form name="upload" id="upload" action="<%=basePath %>ssj/upLoad.action"
method="post" enctype="multipart/form-data" onsubmit="return submitForm()">
<input type="hidden" name="user.userid" value="${user.userid}"/>
<input type="file" name="file" id="file"/>(文件大小不超过100k)<input type="submit" id="upButton" value="上传"/><input type="reset" value="取消"/>
</form>
三、action配置文件
<package name="ssj" namespace="/ssj" extends="struts-default">
<action name="upLoad" class="com.xinfeijinxin.qy.action.PersonalAction"
method="upFile">
<interceptor-ref name="fileUpload" >
<!-- 配置允许上传的文件类型 -->
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg,
image/pjpeg,image/x-png</param>
<!-- 配置允许上传的文件大小100kb -->
<param name="maximumSize">102400</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result >/Personal/Personal_load.jsp</result>
<result name="input">/Personal/Personal_upDownResult.jsp</result>
</action>
</package>
四、文件上传业务代码
public class PersonalAction {
private File file;//上传文件
private String fileFileName;//上传文件名称
private String fileContentType;//上传文件类型
public String upFile()
{
//路径设置
String savePath = ServletActionContext.getServletContext().getRealPath("/images/head");
UpDownLoadFile upFileUtil=new UpDownLoadFile();
String txPath=upFileUtil.saveFile(file, fileFileName, fileContentType, savePath);
return SUCCESS;
}
}