引用
1.gsp 上传页面代码
<g:form controller="document" action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" /> <g:select name="purCategory.id" from="${purcatelist}" optionKey="id" value="${documentInstance?.purCategory?.id}" />
<input type="submit" value="上 传" />
</g:form>
注:enctype="multipart/form-data" 必须要写
引用
2.controller 里的代码
def upload = {
def documentInstance = new Document(params)
def url = params.myFile
// println url
def f = request.getFile('myFile')
if(!f.empty) {
def webRootDir = servletContext.getRealPath("/")
println webRootDir
def userDir = new File(webRootDir, "/payload/")
userDir.mkdirs()
f.transferTo( new File( userDir, f.originalFilename))
documentInstance.fileName = f.originalFilename
}
documentInstance.save()
documentInstance.errors.each{
println it
}
if(!documentInstance.hasErrors() && documentInstance.save()) {
flash.message = "上传成功"
redirect(action:show,id:documentInstance.id)
}
else {
render(view:'create',model:[documentInstance:documentInstance])
}
}
引用
3.下载1
可以直接在gsp页面下载 gsp上的代码
<g:each in="${documentInstanceList}" status="j" var="document">
<tr>
<td width="640" nowrap="nowrap" style="padding: 0 15px;border-bottom:1px #CCC dashed;">${fieldValue(bean:document, field:'title')}</td>
td width="64" height="40" class="table_link" style="border-bottom:1px #CCC dashed;">
<a href="${request.getContextPath()}/payload/${document.fileName}" target="_blank">下载</a></td>
</tr>
</g:each>
下载2
在controller里写下载action
def download = {
def documentInstance = Document.get(params.id)
def filename = documentInstance.fileName
// println filename
response.setHeader("Content-disposition", "attachment; filename=" + filename)
response.contentType = ""
def webRootDir = servletContext.getRealPath("/")
def filepath = new File(webRootDir, "/upload/${filename}")
//def filepath = "E:/founderweb/web-app/upload/${filename}"
// println filepath
def out = response.outputStream
def inputStream = new FileInputStream(filepath)
byte[] buffer = new byte[1024]
int i = -1
while ((i = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, i)
}
out.flush()
out.close()
inputStream.close()
}
页面gsp上代码
<g:link controller="document" action="download" id="${document.id}" target="_blank">下载</g:link>
引用
4.判断文件后缀名
int i = filename.LastIndexOf("."); //取得文件名中最后一个"."的索引
string newext = filename.Substring(i); //获取文件扩展名
if (newext != ".gif" && newext != ".jpg" && newext != ".jpeg" && newext != ".bmp" && newext != ".png")
{
Response.Write("文件格式不正确,请上传gif、jpg、jpeg、bmp及png的格式图片文件!");
Response.End();
}
引用
5.判断文件上传大小
if(f.size>10240){
}
else{
}
引用
6.把上传文件名称以时间命名
def sdf = new SimpleDateFormat("yyyyMMddHHmmssS")//格式化时间输出
def rname = sdf.format(new Date())//取得当前时间,Date()是java.util包里的,这作为真实名称
// println rname
def name = f.originalFilename//得到上传文件的原名称
//println name
int i = name.lastIndexOf(".")//原名称里倒数第一个"."在哪里
def ext = name.substring(i+1)//取得后缀,及"."后面的字符
name = rname+"."+ext//拼凑而成