2015-06-25 198 views
3

我已經使用下面的代碼從圖像src獲取base64字符串,但它不起作用。從圖像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]); 
    } 
} 
控制器

,如何讓作爲一個base64字符串 'imageValue時' 的價值?

當前我正在獲取'imageValue'的一個大字符串的值。

+3

將文件上傳到服務器然後將其轉換爲base64將會更容易。 –

+0

我使用ajax窗體,所以我不能使用HttpPostedFileBase,也在控制器中我得到'imageValue'的一個非常大的字符串的值 –

回答

1

下面我粘貼了比所需的更多的問題。

一旦你選擇了一個文件,這將得到Base64String,這將顯示在<div id="base"></div>

假設您想將文件存儲在您的項目中,那麼保存功能也是存在的。 :)

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> 

首頁控制器>轉換動作

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); 
    } 
} 
+0

在這裏我得到e.target.result一個非常大的字符串。 –

+0

是的,這是您選擇的圖像的Base64String。 – shammelburg

+0

也使用我的代碼時,我得到這個字符串,但它是一個較大的字符串與base64字符串。 –

0

嘗試像這樣用ajax/JavaScript的...這將使用AJAX數據參數發佈的base64字符串控制器作爲datauri參數傳遞給控制器​​。

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); 
    } 

輔助方法...這將給出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(); 
}