【问题标题】:Upload resized form image to server将调整大小的表单图像上传到服务器
【发布时间】:2016-07-20 14:01:56
【问题描述】:

我想将调整大小的图像上传到服务器,但是当我尝试上传调整大小的图像时出现“必需的 MultipartFile 参数‘文件’不存在”错误。当我从那里上传原始文件时没有问题。

脚本:

function resizeAndUpload(file) {
    var reader = new FileReader();
    reader.onloadend = function () {

        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function () {

            var MAX_WIDTH = 200;
            var MAX_HEIGHT = 200;
            var tempW = tempImg.width;
            var tempH = tempImg.height;
            if (tempW > tempH) {
                if (tempW > MAX_WIDTH) {
                    tempH *= MAX_WIDTH / tempW;
                    tempW = MAX_WIDTH;
                }
            } else {
                if (tempH > MAX_HEIGHT) {
                    tempW *= MAX_HEIGHT / tempH;
                    tempH = MAX_HEIGHT;
                }
            }

            var canvas = document.createElement('canvas');
            canvas.width = tempW;
            canvas.height = tempH;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0, tempW, tempH);
            var dataURL = canvas.toDataURL("image/jpeg");

            var data = new FormData();
            data.append('file', dataURL);

            $.ajax({
                url: '/changeimage',
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function () {
                    window.alert("uploaded")
                }
            });
        }
    }
    reader.readAsDataURL(file);
}

服务器:

@RequestMapping(value = "/changeimage", method = RequestMethod.POST)
@ResponseBody
public String changeProfileImage(@Context HttpServletRequest request, @RequestParam("file") MultipartFile file) {
    return "ok";
}

【问题讨论】:

    标签: javascript html ajax upload


    【解决方案1】:

    数据 url 是一个字符串,不会作为文件上传。
    但是,您可以改用blob

        ...
        ctx.drawImage(this, 0, 0, tempW, tempH);
        canvas.toBlob(function(blob){
    
            var data = new FormData();
            data.append('file', blob);
    
            $.ajax({
                url: '/changeimage',
                type: 'POST',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function () {
                    window.alert("uploaded")
                }
            });
        });
        ...
    

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 2015-06-09
      • 1970-01-01
      • 2017-01-08
      • 2022-01-26
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多