如何使用角度js和spring mvc中的多部分形式发送图像和文本值

时间:2016-02-25 08:23:09

标签: angularjs json spring-mvc undefined

到目前为止,我已经尝试了以下代码,我将文本和文件值附加到角度js中的表单数据并将其发送到控制器但是当我提交表单时,我得到415不支持的内容类型错误{{3}在我的控制台中 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

    }

1 个答案:

答案 0 :(得分:0)

我终于找到了一个解决方案,在挣扎一天后添加多张图片。请向上帝和帮助过我的朋友致谢。

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);
}