溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

AngularJS上傳文件的示例代碼

發(fā)布時間:2020-10-17 02:56:48 來源:腳本之家 閱讀:159 作者:嗚嗚嗚啦啦啦 欄目:web開發(fā)

使用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>

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI