//设置上传文件路径
// def webRootDir = servletContext.getRealPath("/");
ConfigObject configObject = ConfigurationHolder.getConfig() //读取配置文件的保存路径
def webRootDir =configObject.getProperty("uploadFileConfig").URLconfig;
def userDir = new File(webRootDir, "/upload");
//println("保存文件路径:"+userDir);
userDir.mkdirs()
//获取上传文件
if(params.dFileNum)
{
int fileInputnum=Integer.parseInt(params.dFileNum); //页面文件控件数量
fileInputnum=fileInputnum+1;
for(int a=1;a<fileInputnum;a++)
{
def fileControl="dFileurl"+a;
// println("控件名:--"+fileControl+"------");
def uploadedFile = request.getFile(fileControl);
//文件上传操作
if(!uploadedFile.empty)
{
// println "Class: ${uploadedFile.class}"
// println "Name: ${uploadedFile.name}"
// println "OriginalFileName: ${uploadedFile.originalFilename}"
// println "Size: ${uploadedFile.size}"
// println "ContentType: ${uploadedFile.contentType}"
//判断文档大小
if( uploadedFile.size>10571168)
{
flash.message ="文档不能超过10M,请重新上传";
params.dFileNum=0;
render(view: "create", model: [articleInstance: articleInstance])
return;
}
// println("文件"+a+"名字:"+uploadedFile.originalFilename);
//保存文件名和文件路径
def fileName=uploadedFile.originalFilename;
def fileID=new Random().nextInt(1000000);
def saveFileName=fileID+"${fileName[fileName.lastIndexOf('.')..-1]}"
//执行上传文件操作
uploadedFile.transferTo( new File( userDir,saveFileName))
if(articleInstance.durlName)
articleInstance.durlName =articleInstance.durlName + fileName+",";
else
articleInstance.durlName = fileName+",";
if(articleInstance.durl)
articleInstance.durl = articleInstance.durl+ saveFileName+",";
else
articleInstance.durl = saveFileName+",";
}
}
}
文件保存需要在数据库建立两个字段:durl 、durlName ,分别用来保存文件的原名和保存在服务器的名字,用","分割
PS:
//判断上传文件格式
switch(uploadedFile.contentType){
case "application/x-zip-compressed": documentInstance.dformat ="rar";break;
case "application/msword": documentInstance.dformat ="doc";break;
case "text/plain": documentInstance.dformat ="txt";break;
case "application/vnd.ms-powerpoint": documentInstance.dformat ="ppt";break;
case "application/vnd.visio": documentInstance.dformat ="visio";break;
case "application/vnd.ms-excel": documentInstance.dformat ="xls";;break;
case "image/gif": documentInstance.dformat ="gif";break;
case "image/pjpeg": documentInstance.dformat ="jpg";break;
}
//判断文档格式是否正确
if( documentInstance.dformat==null)
{
print "不支持的上传文件格式";
flash.message ="不支持的上传文件格式:"+uploadedFile.contentType;
render(view: "create", model: [documentInstance: documentInstance])
return;
}