【问题标题】:how to send image and text values using multipart form in angular js and spring mvc如何在角度js和spring mvc中使用多部分形式发送图像和文本值
【发布时间】:2016-02-25 08:23:08
【问题描述】:

到目前为止,我已经尝试了以下代码,其中我一直在 Angular js 中将文本和文件值附加到表单数据并将其发送到控制器,但是当我提交表单时,我得到 415 unsupported content type error in我的控制台 html

    <html>
<head>
<script src="extensions/angular.min.js"></script>

</head>
<body ng-app="myApp" ng-controller="testcontrol">

    <input type="text" ng-model="A.username" placeholder="Enter Username" required>
    <input type="password" ng-model="A.password" placeholder="Enter Password" required>
    <input type="file"  placeholder="Browse image" name="file" id="test" required>



    <input type="button" value="Send" ng-click="setValues()" />

    <script>


        var app = angular.module('myApp', []);



        app.controller('testcontrol', function($scope, $http) {
            $scope.setValues = function() {
                var formData = new FormData();              
                var file = '#test';
                var json = $scope.A;
                formData.append("file", file);
                formData.append("asd",JSON.stringify(json));

                $http({
                    method : 'POST',
                    url : 'form/upload',
                    headers : {
                        'Content-Type' : 'undefined'
                    },
                    data : formData
                }).success(function(data) {


                    alert(JSON.stringify(data));
                });
            };



        });
    </script>


</body>
</html>

控制器代码

@Controller
@RequestMapping(value="/form")
public class Form {



    @RequestMapping(value = "/upload", method = RequestMethod.POST,consumes = {"multipart/form-data"})
    public @ResponseBody
    void storeAd(@RequestPart("asd") String adString, @RequestPart("file") MultipartFile file) throws IOException {
logger.info("entered controller");
    TestDto1 jsonAd = new ObjectMapper().readValue(adString, TestDto1.class);
//do whatever you want with your file and jsonAd

    }

【问题讨论】:

    标签: angularjs json spring-mvc undefined


    【解决方案1】:

    经过一天的努力,终于找到了添加多张图片的方法。感谢上帝和帮助我的朋友。

    html代码

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script src="extensions/angular.min.js"></script>
    
    
    <script>
        'use strict';
    
        var mainApp = angular.module('mainApp', []);
    
        mainApp.controller('FileUploadController', function($scope, $http) {
    
            $scope.document = {};
    
            $scope.setTitle = function(fileInput) {
                var file = fileInput.value;
                var filename = file.replace(/^.*[\\\/]/, '');
                var title = filename.substr(0, filename.lastIndexOf('.'));
            };
    
            $scope.uploadFile = function() {
    
                var form = document.getElementById('a');
                var formData = new FormData(form);
    
                $scope.dataform = {};
                formData.append('formdata', JSON.stringify($scope.document));
                $http.post('form/up', formData, {
                    transformRequest : function(data, headersGetterFunction) {
                        return data;
                    },
                    headers : {
                        'Content-Type' : undefined
                    }
                }).success(function(data, status) {
                    alert("Success ... " + status);
                }).error(function(data, status) {
                    alert("Error ... " + status);
                });
            };
        });
    </script>
    
    
    </head>
    <body ng-app="mainApp" ng-controller="FileUploadController">
        <form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data" id="a">
    
            <input type="file" name="file[0]" />
            <input type="file" name="file[1]" />
            <br>
            <input type="file" name="filea[0]" />
            <input type="file" name="filea[1]" />
            <br>
            <input type="text" ng-model="document.title" />
            <br>
            <button class="btn btn-primary" type="submit">Submit</button>
        </form>
    </body>
    </html>
    

    这是我的控制器代码

    package com.covenant.app.controllers;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Base64;
    import java.util.Iterator;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.log4j.Logger;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    @Controller
    @RequestMapping(value = "/form")
    public class Form {
    
        @RequestMapping(value = "/up", method = RequestMethod.POST, consumes = { "multipart/form-data" })
        public @ResponseBody void storeAd1(MultipartHttpServletRequest request) {
    
            logger.info("message" + request.getFileNames());
            int i = 0, j = 0;
            Iterator<String> it = request.getFileNames();
            while (it.hasNext()) {
                String s = it.next();
                if (s.startsWith("filea")) {
                    logger.info(request.getFile("filea[" + i + "]").getSize());
                    i++;
                } else {
                    logger.info(request.getFile("file[" + j + "]").getSize());
                    j++;
                }
            }
        }
    
        private static final Logger logger = Logger.getLogger(Form.class);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 2018-05-01
      • 2014-09-05
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多