简体   繁体   English

从ajax向spring控制器发送多部分请求,而没有表格?

[英]Send multipart request from ajax to spring controller without form?

I am uploading an image from the desktop, and converting this image into base code in javascript. 我正在从桌面上传图片,然后将此图片转换为javascript中的基本代码。 After that I want to send this image base code to spring controller with the multipart request. 之后,我想将此图像基本代码与multipart请求一起发送给spring控制器。 But I am not using Form. 但是我没有使用Form。

HTML 的HTML

 <input id="inputFileToLoad" type="file"  onchange="encodeImageFileAsURL()">   

JAVA SCRIPT Java脚本

 window.photoCakeUrl = '<c:url value="/media/image/upload"/>';
      function encodeImageFileAsURL() {
                var filesSelected = document.getElementById("inputFileToLoad").files;
                if (filesSelected.length > 0) {
                    var fileToLoad = filesSelected[0];
                    var fileReader = new FileReader();
                    fileReader.onload = function (fileLoadedEvent) {
                        var srcData = fileLoadedEvent.target.result; // <--- data: base64
                        var newImage = document.createElement('img');
                        var photoCake = srcData;
                        newImage.src = srcData;
                        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
                        var ajax1 = $.ajax({
                            type: 'POST',
                            url: photoCakeUrl,
                            processData: false, // important
                            contentType: false, // important
                            dataType: 'json',
                            data: {photoCak: photoCake}
                        });

                      });

                    },
                            fileReader.readAsDataURL(fileToLoad);
                }
            }

SPRING CONTROLLER: 弹簧控制器:

@RequestMapping(value = "/media/image/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> productPictureUploadnew(MultipartHttpServletRequest request, HttpServletResponse response) {
        Map<String, String> resp = new HashMap<>();
        String photoCake = request.getParameter("photoCak");


        System.out.println("photoCake   " + photoCake);

        return resp;
    }

But when I am generating AJAX call then 500 error will comes. 但是,当我生成AJAX调用时,将出现500错误。 If i am using simply 如果我只是简单地使用

public Map<String, String> productPictureUploadnew(HttpServletRequest
 request, HttpServletResponse response)

Then it works. 然后就可以了。 Mean when I am using MultipartHttpServletRequest place of HttpServletRequest request then it is not works. 意味着当我使用HttpServletRequest请求的 MultipartHttpServletRequest位置时,则它不起作用。

I got solution, We can use formData in javascript without using form in any JSP to send MultipartHttpServletRequest. 我得到了解决方案,我们可以在javascript中使用formData而不在任何JSP中使用form来发送MultipartHttpServletRequest。

 window.photoCakeUrl = '<c:url value="/media/image/upload"/>';
      function encodeImageFileAsURL() {
                var filesSelected = document.getElementById("inputFileToLoad").files;
                if (filesSelected.length > 0) {
                    var fileToLoad = filesSelected[0];
                    var fileReader = new FileReader();
                    fileReader.onload = function (fileLoadedEvent) {
                        var srcData = fileLoadedEvent.target.result; // <--- data: base64
                        var newImage = document.createElement('img');
                        var photoCake = srcData;
                        newImage.src = srcData;
                        document.getElementById("imgTest").innerHTML = newImage.outerHTML;

                        var formData = new FormData();
                        formData.append("imgFile", document.getElementById("inputFileToLoad").files[0]);

                        var ajax1 = $.ajax({
                            type: 'POST',
                            url: photoCakeUrl,
                            dataType: 'json',
                            data: {photoCak: photoCake}
                        });

                      });

                    },
                            fileReader.readAsDataURL(fileToLoad);
                }
            }

var formData = new FormData(); var formData = new FormData();
formData.append("imgFile", document.getElementById("inputFileToLoad").files[0]); formData.append(“ imgFile”,document.getElementById(“ inputFileToLoad”)。files [0]);

Controller: 控制器:

 @RequestMapping(value = "/media/image/upload", method = RequestMethod.POST)
        @ResponseBody
        public Map<String, String> productPictureUploadnew(MultipartHttpServletRequest request, HttpServletResponse response) {
            Map<String, String> resp = new HashMap<>();
            System.out.println("fsasasafsafsafsafsa");
            Iterator<String> itr = request.getFileNames();

            String photoCake = request.getParameter("photoCak");
            File file;
          ----------
           -------
          ----------              

            return resp;
        }

Thanks you, I hope this is help full for you guys. 谢谢,希望对您有帮助。

You are sending it as multipart/form-data may be that's why HttpServletRequest isn't able to get your data , remove contentType option from ajax call then jquery will use the defaylt wiz. 您将其作为multipart / form-data发送时,这可能就是HttpServletRequest无法获取数据的原因,从ajax调用中删除contentType选项,然后jquery将使用defaylt wiz。 'application/x-www-form-urlencoded; 'application / x-www-form-urlencoded; charset=UTF-8' charset = UTF-8'

var ajax1 = $.ajax({
                       type: 'POST',
                        url: photoCakeUrl,
                        processData: false, // important
                        dataType: 'json',
                        data: {photoCak: photoCake}
                    });

This is how I would have done it: 这就是我要做的:

window.photoCakeUrl = '<c:url value="/media/image/upload"/>';
window.URL = window.URL || window.webkitURL

function encodeImageFileAsURL() {
  var filesSelected = $('#inputFileToLoad')[0].files;

  if (filesSelected.length) {
    var fileToLoad = filesSelected[0];
    var img = new Image();
    var formData = new FormData();

    formData.append('imgFile', fileToLoad);

    img.onload = function() {
      // only append the image once it's loaded so we don't append broken images
      $('#imgTest').html(this);
      URL.revokeObjectURL(this.src); // Release memory
      // Uploading a image when we can ensure it's a image that can be loaded
      fetch(photoCakeUrl, {method: 'POST', body: formData});
    }

    img.onerror = function() {
      // You didn't upload a image
    }

    img.src = URL.createObjectURL(srcData);
  }
}
  • URL.createObjectURL is faster and uses less memory then a long base64 string that is also ~3x larger in size and uses 2x more memory since it's stored in utf16 and not utf8 URL.createObjectURL 速度更快 ,使用的内存更少,而长的base64字符串也更大,其大小约为3倍,并且使用的内存多2倍,因为它存储在utf16中而不是utf8中
  • You can use new Image which is a nicer sorter version of createElement('img') 您可以使用new Image ,它是createElement('img')的更好分类器版本
  • Then I would also use Fetch instead of $.ajax cuz jQuery handle formData stupidly (need to set processData & contentType to false) 然后我也将使用Fetch代替$.ajax cuz jQuery愚蠢地处理formData(需要将processData&contentType设置为false)
  • Then i would also add the accept="images/*" attribute to the file input to filter out images 然后,我还将在文件输入中添加accept="images/*"属性以过滤掉图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM