问题描述
将大文件(> 1GB)上载到grails,我只需要通过流访问它,而无需将整个文件保存到磁盘或RAM.但是,如何访问上传流?我尝试了一个拦截器:
Uploading a large file (>1GB) to a grails, I only need to access it via stream, no need to save the entire file to disk or RAM. However how can I access the upload stream? I tried with an Interceptor:
class UploadLargeFileInterceptor {
int order = HIGHEST_PRECEDENCE
UploadLargeFileInterceptor() {
match(controller:"apiv2", action:"uploadLarge")
}
boolean before() {
log.error('before')
log.error(request.getInputStream().text.length() as String)
true
}
boolean after() {
log.error('after')
true
}
void afterView() {
// no-op
}
}
,但是流长度始终为0,并且在控制器中有一个多部分文件,我试图避免该文件,因为它将存储整个文件.有什么想法吗?
but stream length is always 0 and in the controller there is a multipart file which I am trying to avoid because it will store the whole file. Any ideas?
推荐答案
无需拦截器.您可以在控制器内部访问用户上传的文件流,如下所示:
No need for an interceptor. You can access user uploaded file stream like this inside controller:
MultipartFile uploadedFile = params.filename as MultipartFile
println "file original name" + uploadedFile.originalFilename
println "file content type" + uploadedFile.contentType
println "file size" + uploadedFile.size //consider as stream length
InputStream inputStream = uploadedFile.getInputStream() //access the input stream
还要确保在 application.groovy
中允许这样的最大大小:
Also make sure to allow max size in application.groovy
like this:
grails.controllers.upload.maxFileSize = 1572864000 //1500MB (X MB * 1024 * 1024)
grails.controllers.upload.maxRequestSize = 1572864000 //1500MB
或者,如果您正在像 nginx
这样的网络服务器上落后,请调整该请求&超时配置也是如此.
Or if you are running behind on webserver like nginx
, tune that request & timeout config also.
使用上面的代码和 -Xms512m -Xmx1G
堆大小,我上传了1.25Gb文件,没有问题.如果要上传到文件存储/云存储,请确保lib使用流:
With the above code and -Xms512m -Xmx1G
heap size I uploaded 1.25Gb file with no issue. If you are uploading to file storage / cloud storage, make sure that lib uses stream like:
文件: org.apache.commons.io.FileUtils.copyToFile(inputStream,new File('< file path>'))
Azure: storageBlob.upload(inputStream,length)
这篇关于将大文件(大于1GB)上传到grails3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!