6.1.9 上传文件 - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
6.1.9 上传文件
Programmatic File Uploads
Grails supports file uploads using Spring's MultipartHttpServletRequest interface. The first step for file uploading is to create a multipart form like this:Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>
uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard <g:form> tag.There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance directly:def upload() {
def f = request.getFile('myFile')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
} f.transferTo(new File('/some/local/dir/myfile.txt'))
response.sendError(200, 'Done')
}InputStream and so on with the MultipartFile interface.
上传文件编程
Grails通过Spring的MultipartHttpServletRequest接口来支持文件上传。第一步就是要为文件上传创建一个multipart的表单,比如:Upload Form: <br /> <g:uploadForm action="upload"> <input type="file" name="myFile" /> <input type="submit" /> </g:uploadForm>
uploadForm标签在标准<g:form>标签的基础上添加了enctype="multipart/form-data"属性。此后就可以采用多种方式来处理文件上传。其一就是直接使用Spring的MultipartFile:def upload() {
def f = request.getFile('myFile')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
} f.transferTo(new File('/some/local/dir/myfile.txt'))
response.sendError(200, 'Done')
}InputStream来操作文件等,不过这都依赖于MultipartFile接口。File Uploads through Data Binding
File uploads can also be performed using data binding. Consider thisImage domain class:class Image {
byte[] myFile static constraints = {
// Limit upload file size to 2MB
myFile maxSize: 1024 * 1024 * 2
}
}params object in the constructor as in the example below, Grails will automatically bind the file's contents as a byte to the myFile property:def img = new Image(params)byte properties.It is also possible to set the contents of the file as a string by changing the type of the myFile property on the image to a String type:class Image {
String myFile
}文件上传和数据绑定
文件上传也可以通过数据绑定来完成。假设如下的Image领域类:class Image {
byte[] myFile static constraints = {
// Limit upload file size to 2MB
myFile maxSize: 1024 * 1024 * 2
}
}params的构造方法来创建一个图像(image),那么Grails将会自动地把文件内容转换为byte,并且绑定到myFile属性上:def img = new Image(params)byte的,H2和MySQL缺省的blob大小是255字节。你也可以将myFile属性的类型改成字符串来保存文件的内容:class Image {
String myFile
}
