我有一个页面,该页面允许随着时间的推移逐步构建PDF文件(将信息保存到数据库)。我还添加了保存图像的功能。我目前有一个<g:uploadForm>
,将文件发送回 Controller 中的upload
方法(然后调用服务)。但是,上传完成后,Grails尝试渲染与upload
方法关联的 View ,该 View 最终变成空白页。我希望具有无需重新加载 View 就可以将文件发送到后端Grails的功能(因为它将删除输入但未保存的任何数据)。我也有一个使用JavaScript的工作版本,可以向Grails服务器发出AJAX请求,但是我更喜欢Grails解决方案。
这是GSP的相关部分:
<g:uploadForm action="upload" useToken="true" id="5">
<div class="chooseFileButtonContainer">
<input type="file" name="imgfile" class="chooseFileButton" />
</div>
<div class="uploadFileButtonContainer">
<input type="button" value="Upload File" />
</div>
</g:uploadForm>
这是 Controller :
def uploadToSP() {
if (params.imgfile) {
if (params.imgfile instanceof org.springframework.web.multipart.commons.CommonsMultipartFile) {
def (sectionID, reportID) = params.id.tokenize(':')
try {
Service.upload(params.imgfile, sectionID, reportID)
} catch (Exception e) {
System.err << "Upload Failed : " + e.getMessage() +"\n"
}
} else {
System.err << "Invalid file format\nExpected org.springframework.web.multipart.commons.CommonsMultipartFile\nGot ${params.imgfile.getClass()}\n"
}
} else {
System.err << "No file supplied\n"
}
response.sendError(200, "Done")
}
除了单击
Upload
按钮后,所有内容都运行良好,它会转到类似于mysite.com/myapplication/controller/upload/id:id
的URL,该URL只是一个空白页面(/id:id
部分是故意的)。我可以使用JavaScript做到这一点,但是我对仅Groovy / Grails的解决方案感兴趣。 我的问题是如何在不加载新 View 的情况下使用 Controller 方法。
最佳答案
通常,听起来您需要查看对请求和上载的ajax处理,而不只是一个完整的请求/响应周期。关于如何使用JQuery,纯JavaScript或实际上要使用的任何框架上载文件的例子很多。看一看这些,我想您会发现它为您提供了所需的解决方案。
关于grails - 如何在Grails Controller 中调用方法而不渲染新 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290671/