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

时间:2022-05-19 22:10:41

I have tried the following code so far where i have been appending text and file values to the form data in angular js and sending it to the controller but when i submit the form i get 415 unsupported content type error如何使用角度js和spring mvc中的多部分形式发送图像和文本值 in my console html

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

    <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 code

@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 个解决方案

#1


0  

I have finally found a solution to add multiple images after struggling for one day.Praise be to God and my friend who have helped me.

我终于找到了一个解决方案,在奋斗了一天之后添加了多个图像。请向上帝和帮助我的朋友致敬。

html code

<!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>

This is my controller code

这是我的控制器代码

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

#1


0  

I have finally found a solution to add multiple images after struggling for one day.Praise be to God and my friend who have helped me.

我终于找到了一个解决方案,在奋斗了一天之后添加了多个图像。请向上帝和帮助我的朋友致敬。

html code

<!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>

This is my controller code

这是我的控制器代码

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