AngularJS上传文件的示例代码

雪花,是世界上最圣洁的花,当你静静的倾听天籁,尘世的浮躁与喧嚣,似乎都已离你远去,剩下的惟有纯净,那是心灵忘却一切的畅然,那是在没有尘埃的世界里,生命自由呼吸的平淡与安恬。

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

本文AngularJS上传文件的示例代码到此结束。蝴蝶需要一次蜕变,才有可能换来惊艳。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
JS获取鼠标点击时的位置

vue、nginx部署后刷新报404错误的解决方法

electron-builder配置项

VUE聊天页面自动滚动到底部

VUE CTRL+ENTER换行,ENTER发送消息