【问题标题】:Upload a file along with other data to MySQL DB using AngularJS, REST,Hibernate使用 AngularJS、REST、Hibernate 将文件和其他数据上传到 MySQL DB
【发布时间】:2016-08-02 08:48:21
【问题描述】:

我正在尝试使用 AngularJS、REST(在中间层)和 Hibernate(DAO) 将文件以及其他一些数据(名称、描述等)上传到 MySQL DB。

我尝试了很多解决方案,包括创建自己的directive,但我仍然无法做到。

而且我没有在我的jsp 中使用<form> 来提交。而不是那个,我在结尾使用ng-click=submit()

怀疑:-

  1. 文件类型的 DTO 和 DAO 对象的数据类型? (byte[]blob)。

  2. 如何将文件绑定到$scope.data,其中data 包含所有其他信息以及file

  3. $http.post(url,$scope.data)。如何在 REST 方法中访问它。

@Consumes(??) Response function add(DTO object){ //CALL TO DAO AND RETURN RESPOSNE }

我已经尝试过webpage 上的代码,但如何通过REST 处理它仍然是个问题?

如果您为此发布基本代码 sn-p 会更好

【问题讨论】:

    标签: java angularjs rest


    【解决方案1】:

    这是我一年前在我的项目中使用的方式。你可以试试:

    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.
    }
    

    我用这种方式上传图片和音频文件。希望上面的一些sn-ps代码有用。

    【讨论】:

    • 感谢 sn-p。我使用了FileReader 而不是FormData,因为我没有在我的html 中使用表单。
    猜你喜欢
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2014-08-08
    • 2015-04-10
    • 2010-11-21
    • 2015-06-28
    相关资源
    最近更新 更多