這是一個基本的代碼片段是我一年前使用的IM我的項目的方式。你可以嘗試:
HTML:
<form id="signupform" name="signupform" ng-submit="createUser()">
<label for="email">Email</label>
<input type="email" ng-model="regisUser.email" ng-minlength="3" required />
<label for="username">Username</label>
<input type="text" ng-model="regisUser.username" required />
//File upload
<input type="file" name="file" required>
<button id="btn-signup" type="submit">Save</button>
</form>
AngularJS控制器:
// create new user
$scope.createUser = function(){
var formData = new FormData();
formData.append("username", $scope.regisUser.username);
formData.append("email", $scope.regisUser.email);
formData.append("avatar", document.forms['signupform'].file.files[0]);
$http({
method: 'POST',
url: '/api/users',
headers: {'Content-Type': undefined},
data: formData
})
.success(function(data, status) {
...
})
.error(function(data, status){
...
});
};
注意headers: {'Content-Type': undefined}
是非常重要的。別忘了:)
春控制器:
@RequestMapping(value = "/api/users", method = RequestMethod.POST)
public Response insert(@RequestParam String username, @RequestParam String email, @RequestParam(required = false) MultipartFile avatar) {
// now you can get avatar as file that was uploaded from client.
}
我用這樣的方式來上傳圖片和音頻文件。希望以上代碼片段是有用的。
感謝您的片段。我已經使用'FileReader'而不是'FormData',因爲我沒有在我的HTML中使用表格。 –