【问题标题】:Get base64 string from image src从图像 src 中获取 base64 字符串
【发布时间】:2015-06-25 09:38:53
【问题描述】:

我已经使用下面的代码从图像 src 中获取 base64 字符串,但它不起作用。

<input type="file" name="fileUpload" id="fileUpload" onchange="showimagepreview(this)" />
<input type="hidden" id="imageValue" name="imageValue" />
function showimagepreview(input) {
    if (input.files && input.files[0]) {
        var filerdr = new FileReader();
        filerdr.onload = function (e) {
            $('#imgprvw').attr('src', e.target.result);

            $('#imageValue').val(e.target.result);
        }
        filerdr.readAsDataURL(input.files[0]);
    }
}

在控制器中,如何获取'imageValue'的值作为base64字符串?

目前我正在获取一个大字符串的“imageValue”值。

【问题讨论】:

  • 将文件上传到服务器然后在那里转换为base64会更容易。
  • 我使用的是 ajax 形式,所以我不能使用 HttpPostedFileBase,同样在控制器中我得到一个非常大的字符串的 'imageValue' 值

标签: c# jquery asp.net-mvc


【解决方案1】:

我在下面粘贴了超出所需问题的内容。

一旦您选择了一个文件,这将获得 Base64String,这将在 &lt;div id="base"&gt;&lt;/div&gt; 中显示它。

假设您想将文件存储在项目中,保存功能也在那里。 :)

HTML

<input type='file' id="file-upload" />
<img id="img" src="" />
<div id="base"></div>
<button id="save">save</button>

JavaScript

<script>

    var base = '';

    function readImage(input) {
        if (input.files && input.files[0]) {
            var FR = new FileReader();
            FR.onload = function (e) {
                $('#img').attr("src", e.target.result);
                $('#base').text(e.target.result);
                base = e.target.result;
            };
            FR.readAsDataURL(input.files[0]);
        }
    }

    $("#file-upload").change(function () {
        readImage(this);
    });

    $('#save').on('click', function () {
        $.post('/Home/Convert', { 'Base64String': base }, function () { alert('Done'); });
    });


</script>

Home 控制器 > 转换动作

public void Convert(string Base64String)
{
    string fileName = "test.jpg";
    string rootpath = Server.MapPath(Path.Combine("~", "Image", fileName));
    ConvertBase64ToFile.ConvertToFile(rootpath, Base64String.Split(',')[1]);
}

将 Base64String 转换为文件的类

public class ConvertBase64ToFile
{
    public static void ConvertToFile(string location, string file)
    {
        byte[] bytes = Convert.FromBase64String(file);
        File.WriteAllBytes(location, bytes);
    }
}

【讨论】:

  • 这里我得到 e.target.result 一个非常大的字符串。
  • 是的,那是您选择的图像的 Base64String。
  • 在使用我的代码时,我也得到了这个字符串,但与 base64 字符串相比,它是一个大字符串。
  • 我相信字符串长度取决于您选择的文件的大小。
  • 是的,你是对的,长度取决于文件大小,
【解决方案2】:

使用 ajax / javascript 尝试类似的操作...它将使用作为 datauri 参数传递给控制器​​的 ajax 数据参数将 base64 字符串发布到控制器。

MyFunc 会将图像转换为 base64 并将其发布到操作。

function MyFunc() {
    con.drawImage(v, 0, 0, canvasWidth, canvasHeight);
    var = document.getElementById('imgprvw');
    dataURL = c.toDataURL('image/png');

    var raw_image_data = dataURL.replace(/^data\:image\/\w+\;base64\,/, '');

    $.ajax({
        url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'MySaveController/MySaveAction',
        type: 'POST', dataType: 'json',
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        data:
        {
            datauri: JSON.stringify(raw_image_data),
        },
        error: function (xhr) {
            alert('Error: ' + xhr.statusText);
        },
        success: function (result) {
            alert('Image Saved');
        }
    });
}

在控制器中... MySaveAction 会将 base64 转换为位图,然后保存。

    public ActionResult MySaveAction(string datauri)
    {
        // Some stuff.
        if (datauri.Length > 0)
        {
            Byte[] bitmapData = new Byte[datauri.Length];
            bitmapData = Convert.FromBase64String(FixBase64ForImage(datauri));

            string fileLocationImageName = "C:/MYIMAGE.JPG";

            MemoryStream ms = new MemoryStream(bitmapData);

            using (Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(ms)))
            {
                bitImage.Save(fileLocationImageName, System.Drawing.Imaging.ImageFormat.Jpeg);
                output = fileLocationImageName;
            }
        }

        return Json(output, JsonRequestBehavior.AllowGet);
    }

Helper 方法...这将提供 ajax url 参数所需的请求的完整路径。

public static class PathHelper
{
    public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
    {
        string appPath = string.Empty;

        if (httpRequestBase != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}",
                                    httpRequestBase.Url.Scheme,
                                    httpRequestBase.Url.Host,
                                    httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
                                    httpRequestBase.ApplicationPath);
        }

        if (!appPath.EndsWith("/"))
        {
            appPath += "/";
        }

        return appPath;
    }
}

最后,这是对 base64 字符串的修复...即删除使用 JSON.Stringify 转换 base64 时插入的废话。

public string FixBase64ForImage(string image)
{
    System.Text.StringBuilder sbText = new System.Text.StringBuilder(image, image.Length);

    sbText.Replace("\r\n", String.Empty);
    sbText.Replace(" ", String.Empty);
    sbText.Replace("\"", String.Empty);

    return sbText.ToString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2013-02-03
    • 2020-07-22
    相关资源
    最近更新 更多