AngularJS上傳檔案
阿新 • • 發佈:2018-12-09
一、使用AngularJS
上傳檔案
- 前臺是
Angular
頁面- 後臺使用
SpringBoot/SpirngMVC
上傳檔案
- html
<div>
<input id="fileUpload" type="file" />
<button ng-click="uploadFile()">上傳</button>
</div>
- js
$scope.upload = function(){ var form = new FormData(); var file = document.getElementById("fileUpload").files[0]; form.append('file', file); $http({ method: 'POST', url: '/upload', data: form, headers: {'Content-Type': undefined}, transformRequest: angular.identity }).success(function (data) { console.log('upload success'); }).error(function (data) { console.log('upload fail'); }) }
注意:
- AngularJS預設的'Content-Type'是application/json ,通過設定'Content-Type': undefined,這樣瀏覽器不僅幫我們把Content-Type 設定為 multipart/form-data,還填充上當前的boundary,
- 如果手動設定為:'Content-Type': multipart/form-data,後臺會丟擲異常:the request was rejected because no multipart boundary was found
- boundary 是隨機生成的字串,用來分隔文字的開始和結束
- 通過設定 transformRequest: angular.identity ,anjularjs transformRequest function 將序列化我們的formdata object,也可以不新增
- 後臺
@RequestMapping("/upload") public void uploadFile(@RequestParam(value = "file" , required = true) MultipartFile file) { //deal with file }
注意:
- 檔案必須通過@RequestParam註解來獲取,且需指定value才能獲取到
- 這樣就完成了上傳檔案
上傳檔案的同時傳遞其他引數
- html
<div>
<input id="fileUpload" type="file" />
<button ng-click="ok()">上傳</button><br>
<input ng-model="user.username" />
<input ng-model="user.password" />
</div>
$scope.ok = function () {
var form = new FormData();
var file = document.getElementById("fileUpload").files[0];
var user =JSON.stringify($scope.user);
form.append('file', file);
form.append('user',user);
$http({
method: 'POST',
url: '/addUser',
data: form,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).success(function (data) {
console.log('operation success');
}).error(function (data) {
console.log('operation fail');
})
};
- js
$scope.ok = function () {
var form = new FormData();
var file = document.getElementById("fileUpload").files[0];
var user =JSON.stringify($scope.user);
form.append('file', file);
form.append('user',user);
$http({
method: 'POST',
url: '/addUser',
data: form,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).success(function (data) {
console.log('operation success');
}).error(function (data) {
console.log('operation fail');
})
};
注意
- 需要將Object轉為String後在附加到form上,否則會直接被轉為字串[Object,object]
- 後臺
@RequestMapping("/upload")
public Map<String, Object> upload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "user", required = true) String user) {
try (FileInputStream in = (FileInputStream) headImg.getInputStream();
FileOutputStream out = new FileOutputStream("filePathAndName")) {
//將Json物件解析為UserModel物件
ObjectMapper objectMapper = new ObjectMapper();
UserModel userModel = objectMapper.readValue(user, UserModel.class);
//儲存檔案到filePathAndName
int hasRead = 0;
byte[] bytes = new byte[1024];
while ((hasRead = in.read(bytes)) > 0) {
out.write(bytes, 0, hasRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
注意
ObjectMapper
為com.fasterxml.jackson.databind.ObjectMapper