【发布时间】:2015-09-27 07:35:08
【问题描述】:
我正在尝试使用 GRAILS 通过 REST 上传文件
curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: d5d7aef8-3964-311b-8b64-4a7a82c52323" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "file1=myfile.jpg" -F "fname=swateek" -F "lname=jena" 'http://localhost:8081/sampleFileREST/document/upload'
这是我的控制器的样子:
class DocumentController extends RestfulController<Document> {
static responseFormats = ['json', 'xml']
def upload() {
def fileLocation="<xml>empty</xml>"
def file = request.getParameter('file1')
def f1 = request.getParameter('fname')
def f2 = "<abc>"+request.getParameter('lname')+"</abc>"
def params = "gf"
if(file.empty) {
fileLocation = "<xml>"+"File cannot be empty"+"</xml><allprm>"+params+"</allprm>"
} else {
def documentInstance = new Document()
documentInstance.filename = file.originalFilename
documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
file.transferTo(new File(documentInstance.fullPath))
documentInstance.save()
fileLocation = "<xml>"+documentInstance.fullPath+"</xml>"
}
/* return "File uploaded to: "+documentInstance.fullPath */
render(text: fileLocation, contentType: "text/xml", encoding: "UTF-8")
}
}
我能够访问请求的参数,除了我在请求中发送的文件之外的任何内容。
无法弄清楚这里出了什么问题。
更新
我曾使用 .getParameter() 来获取文件。不对,正确的做法如下:
request.getFile('<filename>') // without the <>
这可能会在 IntelliJ 中引发“未找到符号”或“无法解析方法”的错误,请按照以下答案中的步骤操作。
【问题讨论】:
-
也添加 cURL 标签。同时显示您的 cURL 响应。
-
@EjazAhmed 感谢您抽出宝贵时间。我刚刚解决了。
标签: rest grails groovy postman