个性化阅读
专注于IT技术分析

如何使用jQuery将base64图像转换为图像文件并以异步形式上传

本文概述

当你需要将Base64映像上传到服务器时, 你可能会实现的第一个解决方案, 并且可能是每个人都会想到的唯一想法, 就是将该文件作为字符串上传, 然后将其转换为服务器端的文件。此实现的工作原理很吸引人, 但是如果你不想让服务器为用户完成所有艰苦的工作, 你可能还想知道另一种实现。

在本文中, 你将学习如何将Base64字符串转换为Blob, 并将其作为文件上传到我们的服务器。这种方法等效于用户将文件拖放到文件输入中时所执行的操作。

实现

首先, 我们需要使用Javascript将base64字符串转换为”文件”, 然后将Base64字符串转换为Blob, 并将其解释为服务器中的File。

我们将使用以下方法将base64字符串转换为blob:

/**
 * Convert a base64 string in a Blob according to the data and contentType.
 * 
 * @param b64Data {String} Pure base64 string without contentType
 * @param contentType {String} the content type of the file i.e (image/jpeg - image/png - text/plain)
 * @param sliceSize {Int} SliceSize to process the byteCharacters
 * @see http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
 * @return Blob
 */
function b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

      var blob = new Blob(byteArrays, {type: contentType});
      return blob;
}

现在, 由于你根本无法将Blob附加到可见文件输入中, 因此我们需要使用Post请求以异步形式将其添加。我们将使用以下形式:

<form id="myAwesomeForm" method="post" action="/php-code-that-handles-fileupload.php">
    <input type="text" id="filename" name="filename" /> <!-- Filename -->
    <input type="submit" id="submitButton" name="submitButton" /> <!-- Submit -->
</form>

提交之前的表单只会发送filename参数, 而不发送任何文件。使用Javascript检索表单并将其作为第一个参数传递给FormData的新实例, 该实例将包含输入到异步表单的文本, 此外, 处理你的Base64字符串以适合b64toblob函数所需的格式(第一个参数仅适用于base64字符串(不包含内容类型, 仅作为数据类型的第二个参数):

// Get the form element withot jQuery
var form = document.getElementById("myAwesomeForm");

var ImageURL = "data:image/gif;base64, R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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CJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==";
// Split the base64 string in data and contentType
var block = ImageURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];// In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(", ")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."

// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);

// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);

现在, FormData已经有了一个文件, 你只需要使用jQuery异步提交即可:

/**
 * The following code should send 2 post parameters:
 * filename: providen by the text input
 * image: a file, dinamically added from a base64 string using javascript
 *
 * Is up to you how to receive the file in the Server side.
 */
$.ajax({
    url:"/php-code-that-handles-fileupload.php", data: formDataToUpload, // Add as Data the Previously create formData
    type:"POST", contentType:false, processData:false, cache:false, dataType:"json", // Change this according to your response from the server.
    error:function(err){
        console.error(err);
    }, success:function(data){
        console.log(data);
    }, complete:function(){
        console.log("Request finished.");
    }
});

由你决定如何处理先前的代码, 可以阻止表单的Submit事件, 然后执行代码, 如以下示例所示:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Base64 string to a file in form</title>
    </head>
    <body>
        <form id="myAwesomeForm" method="post" action="endpoint.php">
            <input type="text" id="filename" name="filename" /> <!-- Filename -->
            <input type="submit" id="submitButton" name="submitButton" /> <!-- Submit -->
        </form>
        <script>
            function b64toBlob(b64Data, contentType, sliceSize) {
                contentType = contentType || '';
                sliceSize = sliceSize || 512;

                var byteCharacters = atob(b64Data);
                var byteArrays = [];

                for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                    var slice = byteCharacters.slice(offset, offset + sliceSize);

                    var byteNumbers = new Array(slice.length);
                    for (var i = 0; i < slice.length; i++) {
                        byteNumbers[i] = slice.charCodeAt(i);
                    }

                    var byteArray = new Uint8Array(byteNumbers);

                    byteArrays.push(byteArray);
                }

              var blob = new Blob(byteArrays, {type: contentType});
              return blob;
            }

            $("#myAwesomeForm").submit(function(e){
                e.preventDefault();
                appendFileAndSubmit();
            });

            function appendFileAndSubmit(){
                // Get the form
                var form = document.getElementById("myAwesomeForm");

                var ImageURL = "data:image/gif;base64, R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx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/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==";
                // Split the base64 string in data and contentType
                var block = ImageURL.split(";");
                // Get the content type
                var contentType = block[0].split(":")[1];// In this case "image/gif"
                // get the real base64 content of the file
                var realData = block[1].split(", ")[1];// In this case "iVBORw0KGg...."

                // Convert to blob
                var blob = b64toBlob(realData, contentType);

                // Create a FormData and append the file
                var fd = new FormData(form);
                fd.append("image", blob);

                // Submit Form and upload file
                $.ajax({
                    url:"endpoint.php", data: fd, // the formData function is available in almost all new browsers.
                    type:"POST", contentType:false, processData:false, cache:false, dataType:"json", // Change this according to your response from the server.
                    error:function(err){
                        console.error(err);
                    }, success:function(data){
                        console.log(data);
                    }, complete:function(){
                        console.log("Request finished.");
                    }
                });
            }
        </script>
    </body>
</html>

在服务器端检索文件

由你决定如何在服务器端接收文件, 因为我们不知道你是否在使用PHP, 框架, django或其他语言, 但是, 我们提供了2个PHP示例, 可以帮助你理解我们只是做。

Symfony 2

<?php
// Important to use these statemenets, the json response is optional for our response.
use Symfony\Component\HttpFoundation\Request;

public function retrieveAction(Request $request){
   // retrieve the file with the name given in the form.
   // do var_dump($request->files->all()); if you need to know if the file is being uploaded.
   $file = $request->files->get('image');
   $nameInTextInput = $request->request->get("filename");
}

纯PHP

// Do something with the gif image
$file = $_FILES['image']['tmp_name'];

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何使用jQuery将base64图像转换为图像文件并以异步形式上传

评论 抢沙发

评论前必须登录!