【问题标题】:Unable to upload file via REST request in GRAILS无法通过 GRAILS 中的 REST 请求上传文件
【发布时间】: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


【解决方案1】:

该死的我正在使用的 IDE,IntelliJ

另外,获取文件时的这段代码:

def file = request.getParameter('file1')

应该替换为

def file = request.getFile('file1')

现在,以前,当我使用 request.getFile() 方法时,我收到“未找到符号”错误,并且无法执行请求。

解决方案

  • 打开 IntelliJ
  • 点击“文件”
  • 找到“使缓存无效/重新启动”选项并等待 IntelliJ 再次返回。

如果这不起作用,则此答案中提到了另一种方法: IntelliJ IDEA JDK configuration on Mac OS

【讨论】:

  • 接受这个作为答案。
  • 感谢您的建议,但 stackoverflow 说我必须等待 2 天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
相关资源
最近更新 更多