没有请求正文的多部分会抛出 415



我创建了简单的休息方法,通过 Spring Boot 中的多部分上传和添加文件。我没有任何@RequestBody所以我很惊讶为什么浏览器会抛出415 -> "Unsupported Media Type" Content type 'null' not supported控制器如下所示:

@RestController
@RequestMapping(value = "/api/file")
public class FileController {
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private UserRepository userRepository;
    @PreAuthorize("hasAnyAuthority('CLIENT')")
    @RequestMapping(value = "", method = RequestMethod.POST, headers = "content-type=multipart/*", produces = "application/json", consumes = MediaType.APPLICATION_JSON_VALUE)
    public File uploadFile(@RequestParam("uploadedFile") MultipartFile file, HttpServletRequest httpRequest) {
        Principal name = httpRequest.getUserPrincipal();
        if (name.getName() == null) {
            throw new RuntimeException("Brak sesji");
        }
        User userByLogin = userRepository.findUserByLogin(name.getName());
        File f = null;
        if (!file.isEmpty()) {
            try {
                f = new File(file.getOriginalFilename(), file.getBytes(), file.getName(), file.getContentType(), new Date(), userByLogin);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (f != null) {
            fileService.uploadFile(f);
        }
        return f;
    }
}

在前端看起来像

<div>
<label>Dodaj załącznik</label>
<input type="file" files-model="file" >
<button ng-click="addFile()">Dodaj</button>
</div>
 $scope.addFile = function () {
          FileService.save($scope.file);
 }

失败如下所示:

{"timestamp":1491988354597,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'null' not supported","path":"/api/file"}
您必须将

文件附加到formData中。

<div>
<label></label>
<input type="file" files-model="file" id="file" >
<button ng-click="addFile()">Dodaj</button>
</div>
$scope.addFile = function () {
      var file = document.getElementById("file").files[0];
      var formData = new FormData();
      formData.append("file", file);
      FileService.save(formData);
 };

在文件服务服务中,您必须设置标头:{内容类型:未定义}

这应该有效!

相关内容

  • 没有找到相关文章

最新更新