【问题标题】:405 Method not allowed in Spring MVCSpring MVC 中不允许使用 405 方法
【发布时间】:2016-03-04 08:29:52
【问题描述】:

我使用的是 Spring 4.2.3 版,Spring boot 1.3.0 版。

当我使用 Advanced rest client 将文件上传到我的服务时,我收到了 405 Method Not Allowed 错误。

我的控制器是:

@RequestMapping(value = "/uploadDocXFileMul", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public
@ResponseBody
 HttpEntity<String> upload(@RequestParam("fileUpload") MultipartFile file, @RequestBody FileDTO fileDTO){
    /**
    work with file

    **/
}

我的 FileDTO 是

public class FileDTO implements Serializable {

private static final long serialVersionUID = -211383758881523704L;

@NotEmpty
private String type;
@NotNull
private Date createdDate;
@NotEmpty
private String clientId;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

我的 Rest 客户端图像是

我的错误信息是:

Status
405 Method Not Allowed Show explanation Loading time: 792
Request headers 
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFGAn4APIXqrAvDlW 
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Response headers 
Server: Apache-Coyote/1.1 
Allow: HEAD, GET 
Content-Type: text/html;charset=utf-8 
Content-Language: en 
Content-Length: 1090 
Date: Mon, 30 Nov 2015 16:00:06 GMT 

注意:我对弹簧很陌生,请帮助我

【问题讨论】:

  • 设置content-type header为multipart/form-data,在你的rest客户端默认设置为application/json
  • 我已经通过将其更改为 multipart/form-data 但没有运气
  • 如果您发送文件,它会自动将内容类型标头覆盖为 multipart/form-data - 即使您设置了不同的标头。否则运输将无法工作。

标签: spring spring-mvc file-upload


【解决方案1】:

我认为你的问题是因为

@RequestBody FileDTO fileDTO

这会将您的请求正文映射到对象。但你也告诉 String 你只是 cosume

consumes = MediaType.MULTIPART_FORM_DATA_VALUE

您正在发送表单数据之类的请求,而您的控制器中没有表单映射。

我建议你把它分成两种方法,一种是文件上传,另一种是你的RequestBody,你可以发送json数据而不是表单数据。

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 2018-09-08
    • 2014-06-11
    • 2022-01-07
    • 2016-03-19
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多