Hi bebins,
Refer below sample.
HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var fileName;
$("input[type=file]").change(function (e) {
var file = e.target.files[0];
fileName = e.target.files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
$('#hfBase64').val(e.target.result);
}
if (file) {
reader.readAsDataURL(file);
}
});
$("#btnUpload").on("click", function () {
var base64 = $("#hfBase64").val();
var obj = {};
obj.data = base64;
obj.name = fileName;
$.ajax({
type: 'POST',
url: 'Default.aspx/UploadFile',
data: JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
dataType: 'json', error: function (e) { debugger; }
});
});
});
</script>
<div>
<asp:HiddenField ID="hfBase64" runat="server" />
<asp:FileUpload ID="FileUpload1" runat="server" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<asp:Button Text="Upload" runat="server" ID="btnUpload" />
</div>
Namespaces
C#
using System.Web.Services;
VB.Net
Imports System.Web.Services
Code
C#
[WebMethod]
public static void UploadFile(string data, string name)
{
string base64 = data.Replace("data:application/vnd.ms-excel;base64,", "")
.Replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,", "");
// Saving Base64 string as file.
System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Files/" + name), Convert.FromBase64String(base64));
}
VB.Net
<WebMethod()>
Public Shared Sub UploadFile(ByVal data As String, ByVal name As String)
Dim base64 As String = data.Replace("data:application/vnd.ms-excel;base64,", "").Replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,", "")
' Saving Base64 string as file.
System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Files/" & name), Convert.FromBase64String(base64))
End Sub