简体   繁体   English

通过JQuery AJAX上传图像

[英]Uploading Images via JQuery AJAX

I looked around and just couldn't find what I'm looking for without additional plugins/libraries . 我环顾四周, 没有其他插件/库 ,就是找不到我想要的东西。 I want to upload an image and process it serverside via JQuery AJAX, but I can't figure out how to pass and process it. 我想上传图像并通过JQuery AJAX在服务器端进行处理,但是我不知道如何传递和处理它。 Any help is much appreciated! 任何帮助深表感谢!

Though Diodeus is correct, it isn't quite that difficult. 尽管Diodeus是正确的,但并不是那么困难。 Just maddening. 只是发疯。

HTML5 does expose what is called the FileReader API, which is still relatively new and unsupported on legacy browsers, but which will make your job easier. HTML5确实公开了所谓的FileReader API,它仍然是相对较新的并且在旧版浏览器中不受支持,但它将使您的工作更加轻松。 I have a small app which accepts images on the client side and, using the FileReader API, converts them to base-64 for uploading to the server. 我有一个小应用程序,它可以在客户端接受图像,并使用FileReader API将其转换为base-64,以便上传到服务器。

The following is the function I call upon a user's uploading an image. 以下是我在用户上传图片时调用的功能。 App.FileReader is an instantiation of the HTML5 FileReader, which is declared simply like: App.FileReader是HTML5 FileReader的实例,其声明方式如下:

App.FileReader = window.FileReader ? new FileReader : null;

Upon upload, I read the image as a dataURL using the FileReader, and push the data into an unused tag. 上传后,我使用FileReader将图像读取为dataURL,然后将数据放入未使用的标签中。 The FileReader itself retains the read data, which is why it is a good idea to only instantiate one FileReader at a time. FileReader本身保留读取的数据,这就是为什么一次只实例化一个FileReader是一个好主意的原因。

    if (input.files && input.files[0]) {

        if (App.FileReader) {

            App.FileReader.onload = function (e) {
                $('#createMomentImagePreview').attr('src', e.target.result);
            }

            App.FileReader.readAsDataURL(input.files[0]);

            $this.uploadedImage = true
        }

        else {
            $('#createMomentImagePreview').attr('src', 'http://d33w6ffaa49e6z.cloudfront.net/media/ImageLoaded.png');

            $this.uploadedImage = true
        }
    }

This is the AJAX call for uploading to the server, where data represents the read file, or "App.FileReader.result": 这是用于上传到服务器的AJAX调用,其中数据代表读取的文件或“ App.FileReader.result”:

    $.ajax({
        url: '/image',
        type: 'POST',
        data: {
            image: App.FileReader.result
        }
    }).done(function(data){

        callback(data);

    }).fail(function() {
        console.log("Image upload failed!")
        alert("Sorry, there was an error uploading your image to the database.")
    })

Server-side (and I'm using Node with Express, so this might not apply), I can convert the base64 string to a Buffer (Blob) and send that up to S3 using Knox's putBuffer. 服务器端(并且我将Node与Express一起使用,因此这可能不适用),我可以将base64字符串转换为Buffer(Blob),然后使用Knox的putBuffer将其发送到S3。 This is waaaaaay simpler than actually authenticating with S3 AND trying to get it to play nice with your binary data. 这比实际通过S3进行身份验证并尝试使其与二进制数据配合使用要简单得多。

if (req.body.image.match(/^data:image\/png;base64,/)) {
    var image = new Buffer(req.body.image.replace(/^data:image\/png;base64,/,""), "base64");
}

else if (req.body.image.match(/^data:image\/jpeg;base64,/)) {
    var image = new Buffer(req.body.image.replace(/^data:image\/jpeg;base64,/,""), "base64");
}

awsClient.putBuffer(image, '/' + imagePath + '.jpg', headers, function(err, stream) {

          if (err) {
            console.log(err);
            return false
          }

          res.send(200, imagePath + '.jpg')

          image = null;

        });

In either case, once you have the base64 data on your server you've made significant progress. 无论哪种情况,一旦服务器上有base64数据,您都将取得重大进展。 You could use ImageMagick to handle processing as well. 您也可以使用ImageMagick处理处理。 For what it's worth, I hope this helps you out in some way! 对于它的价值,我希望这可以在某种程度上帮助您!

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

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