export txt file using web api #

export txt file using web api #
 In this article, we are going to see, export txt file using web api #

[HttpGet]
public HttpResponseMessage ExportToText(string delimited)
{
try
{
DataTable table = new DataTable("Employees");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Columns.Add(new DataColumn("Email", typeof(string)));
table.Columns.Add(new DataColumn("Salary", typeof(decimal)));
table.Columns.Add(new DataColumn("Age", typeof(int)));

table.Rows.Add(1, "A", "abc@gmail.com", 95000, 30);
table.Rows.Add(2, "B", "pqr@gmail.com", 96000, 31);
table.Rows.Add(3, "C", "xyz@gmail.com", 97000, 32);

var file = string.Empty;
var filePath = HttpContext.Current.Request.MapPath("~/Uploads/dtEmployees.txt");
if (!File.Exists(filePath))
{
file = Path.GetDirectoryName(filePath);
if (!Directory.Exists(file))
Directory.CreateDirectory(file);
FileStream f1 = File.Create(filePath);
f1.Close();
}
StringBuilder fileContent = new StringBuilder();
fileContent.Append("Id" + delimited + "Name" + delimited + "Email" + delimited + "" + "Salary" + delimited + "Age" + delimited + "");
fileContent.Replace(delimited, System.Environment.NewLine, fileContent.Length - 1, 1);
foreach (DataRow dr in table.Rows)
{
foreach (var column in dr.ItemArray)
{
fileContent.Append("\"" + column.ToString() + "\"" + delimited + "");
}
fileContent.Replace(delimited, System.Environment.NewLine, fileContent.Length - 1, 1);
}
file = filePath;
System.IO.File.WriteAllText(file, fileContent.ToString());
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(File.ReadAllBytes(file))
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Employee.txt" };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/text");
return result;
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}

<a href="javascript:void(0);" id="ExportToText" onclick="ExportToText();">Export to Text</a>

function ExportToText() {
    //window.open('/api/Employee/ExportToText', '_self', '');
    var del = ",";
    try {
        $.ajax({
            method: "GET",
            url: _apiOrderViewer + "/ExportToText?delimited=" + del,
            success: function (response, status, xhr) {
                //check for a filename
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                var type = xhr.getResponseHeader('Content-Type');
                var blob = new Blob([response], { type: type });
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);
                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        var a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }
                    setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                }
            },
            error: function (e) {
                e.toString();
            }
        });
    } catch (e) {
        e.toString();
    }
}

Post a Comment

0 Comments