没有RequestBody的Multipart抛出415

时间:2017-04-12 09:12:58

标签: angularjs spring spring-boot multipart

我已经创建了简单的rest方法来在Spring Boot中通过multipart上传和添加文件。 我没有任何@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"}

1 个答案:

答案 0 :(得分:0)

你必须在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);
 };

在FileService服务中,您必须设置标题:{Content-Type:undefined}

这应该有用!