【问题标题】:java Spring boot get the file name in the controller when post request is sent via curljava Spring boot在通过curl发送post请求时获取控制器中的文件名
【发布时间】:2018-08-16 05:45:29
【问题描述】:

我正在尝试将文件从客户端上传到服务器,客户端使用 curl 命令将文件上传到服务器

客户端命令:

curl -X POST -T pom.xml http://localhost:8070/put --header "origmd5":"7AB4E6F0A4A2D3CBB200DB1677D99AD75"

现在在控制器中,即在服务器端,代码如下

服务器端:

@PostMapping(value="readFile")
public ResponseEntity<?> uploadfile(@RequestBody String filecontent) throws IllegalStateException, IOException {
System.out.println(filecontent);//prints the content which is inside the file uploaded by client
  return null;
  }

1.现在的问题说明是如何获取客户端已经发送的文件名,文件的内容可以在请求体中解析,但是如何获取文件名呢?

 @RequestBody String filecontent

2.我使用上面的字符串来解析请求正文(即文件内容存储在字符串中)这是将文件内容存储在字符串中的正确方法吗?

【问题讨论】:

  • 如果文件是请求的正文,则不能。您必须在请求中添加一个附加参数。

标签: java spring web-services spring-mvc spring-boot


【解决方案1】:

您实际上需要MultipartFile,它将为您提供与上传文件相关的所有信息。

uploadfile(@RequestParam("file") MultipartFile file){
String fileName = file.getOriginalFilename()
}

【讨论】:

  • 谢谢!。我知道它可以通过指定请求参数来工作,但我想上传而不在客户端指定文件参数
  • 我不确定这是否可能。您必须为上传的数据命名,以便 SpringBoot 可以在 Controller 层绑定它。顺便说一句,为什么会有这个奇怪的要求?
  • @saitejapakalapati 无论如何,您必须将文件信息上传到后端以使其知道名称
  • @saitejapakalapati 您不能仅通过文件名上传文件。你必须有 multipartFile
【解决方案2】:

在上传文件时使用 Multipart 可能是更好的解决方案:

@PostMapping(value="readFile")
public ResponseEntity<?> uploadfile(@RequestParam(value="file") MultipartFile fileContent){

}

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多