imageupload works in local but does not work in server - ajax

I want to upload a image on server.I use ajax and webmethod, It works when I run code in local host but when I upload it in server it does not work.
I guess there are some problems in my webmethod but I could not find it.
function savefile(location, files, method_name) {
var data = new FormData();
var webmethod = "../WebService.asmx/" + method-name;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
data.append("location", location);
}
var ajaxRequest = $.ajax({
type: "POST",
url: webmethod,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: data
});
}
<WebMethod(EnableSession:=True)> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function savefile() As String
Try
Dim result As String = ""
Dim pdf As String = ""
If HttpContext.Current.Request.Files.AllKeys.Any() Then
Dim httpPostedFile = HttpContext.Current.Request.Files("UploadedFile")
If httpPostedFile IsNot Nothing Then
Dim location = HttpContext.Current.Request("location")
Dim extension As String = System.IO.Path.GetExtension(httpPostedFile.FileName)
Dim filename_widthout_extension As String = httpPostedFile.FileName.Substring(0, httpPostedFile.FileName.Length - extension.Length)
Dim file_name = httpPostedFile.FileName
Dim fileSavePath = System.IO.Path.Combine(Server.MapPath(HttpContext.Current.Request("location").ToString), filename_widthout_extension + postfix + extension)
result = (location + "/" + filename_widthout_extension + extension).ToString.Substring(2)
httpPostedFile.SaveAs(fileSavePath)
location = httpPostedFile.FileName
End If
Return ""
Catch ex As Exception
End Try
End Function

Related

Download Excel sheet from .NET Core 3.1 Web API with jQuery Ajax client

I am trying to download an Excel file returned by the Web API using an Ajax client. When I try to hit the end point using Swagger, it returns the file and I can download it, but when I am trying through Ajax client, I am still able to download the file, but the file contents is corrupted and I cannot open it.
API code:
using (var workbook = new XLWorkbook())
{
var inspections = await _inspectionRepository.GetInspectionsForExcel(username, userStatus, usertype);
var worksheet = workbook.Worksheets.Add("Inspections");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "Type";
worksheet.Cell(currentRow, 2).Value = "Area";
worksheet.Cell(currentRow, 3).Value = "Site";
worksheet.Cell(currentRow, 4).Value = "Date";
worksheet.Cell(currentRow, 5).Value = "Status";
worksheet.Cell(currentRow, 6).Value = "Reference Number";
foreach (var inspection in inspections)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = inspection.Interval;
worksheet.Cell(currentRow, 2).Value = inspection.Area;
worksheet.Cell(currentRow, 3).Value = inspection.InspectionSiteName;
worksheet.Cell(currentRow, 4).Value = inspection.Date;
worksheet.Cell(currentRow, 5).Value = inspection.StatusName;
worksheet.Cell(currentRow, 6).Value = inspection.RefNumber;
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Inspections.xlsx");
}
}
Ajax client code
$.ajax({
url: baseUri + 'api/CorporateSecurityInspection/ExportExcel/' + username + "/" + userStatus + "/" + userType,
type: 'post',
contentType: 'application/json',
success: function (data) {
console.log(data);
//var a = document.createElement('a');
//var binaryData = [];
//binaryData.push(data);
//var url = window.URL.createObjectURL(new Blob(binaryData));
//a.href = url;
//a.download = 'Inspection.xlsx';
//document.body.append(a);
//a.click();
//a.remove();
//window.URL.revokeObjectURL(url);
var blob = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", "Inspection.xlsx");
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
error: function () {
}
});
Using Swagger I am able to get the file and download it:
After getting downloading file using ajax client I get this error:

i cant export my list to csv using mvc c#

I have been dealing with a problem for hours,kindly help me,the following is my ajax which post data to controller :
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("CreateCSVFile ","Turbine ")",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(data),
success: function(result) {}
})
It posts the result I want to controller,but problem starts from here that in my controller after making the export file,i don't see any thing in the browser to save it,i have no idea where is going wrong,the following is my controller:
public FileContentResult CreateCSVFile(string turbinename, string frm_date, string to_date)
{
var eventResult = (from c in DB.Events
where (c.m_turbine_id == turbineid.turbineID) && (c.m_time_stamp >= frmDate && c.m_time_stamp <= toDate)
select new EventLogPartialViewModel
{
Timestamp = c.m_time_stamp,
Description = c.m_event_log_description,
WindSpeed = c.m_wind_speed,
RPM = c.m_rpm,
Power = c.m_power
}).ToList().Select(x => new
{
Timestamp = x.Timestamp.ToString("dd/MM/yyyy H:mm:ss"),
Description = x.Description,
WindSpeed = x.WindSpeed,
RPM = x.RPM,
Power = x.Power
}).ToList().OrderByDescending(m => m.Timestamp);
var st = DataTag.NoExclusion;
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = ASCIIEncoding.ASCII.GetBytes(CSVExport.GetCsv(eventResult.ToList(), st));
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
}
To fit your particular function, you can do :
public FileContentResult CreateCSVFile()
{
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = Encoding.UTF8.GetBytes(csv); // or get your bytes the way you want
string contentType = "text/csv";
var result = new FileContentResult(csvBytes, contentType);
return result;
}
This is how you can create a FileContentResult.
However, I prefer to use this to send a response with a file :
[HttpGet]
public HttpResponseMessage GetYourFile()
{
string csv = "Charlie, Chaplin, Chuckles";
byte[] csvBytes = Encoding.UTF8.GetBytes(csv); // or get your bytes the way you want
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(csvBytes);
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "YourFileName.csv"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("text/csv");
return result;
}
(adapted from How to return a file (FileContentResult) in ASP.NET WebAPI).
Extracting the "csv" part in bytes is another problem completely, I hope your problem was about the "create a file" part.

PareserError Function was not called

I am getting this error and I do not know how to get passed it. I am trying to do an ajax call to populate my data store. The error is:
Parsererror 'function' was not called when I do this :
var customStore = new DevExpress.data.CustomStore({
load: function () {
return $.ajax({
url: 'URL/Service/GetCustomers?callback=?fnsuccesscallback',
crossOrigin: true,
crossDomain: true,
jsonp: true,
type: 'GET',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'fnsuccesscallback',
async: false,
success: function (res) {
console.log("success");
res = JSON.parse(res);
console.log("data _" + res);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
}
});
var fnsuccesscallback = function (data) {
alert(data);
};
var gridDataSourceConfiguration = {
store: customStore
};
My Service code for this function is :
Function GetCustomers() As Stream Implements IService.GetCustomers
Try
Dim Cust As List(Of Customers) = New List(Of Customers)
Dim SQLSTR As String = ""
SQLSTR = "Select Code, Name, ID FROM Table"
Dim ErrorMessage As String = ""
ErrorMessage = Obj.OpenConnection(SQLServer, UmbrellaDatabase, UserCode, UserPassword)
If ErrorMessage <> "" Then
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Return Nothing
Else
Dim CustomerDetails As DataSet
CustomerDetails = tObj.GetDataSQL(SQLSTR)
If Not CustomerDetails Is Nothing Then
CustomerDetails.DataSetName = "Companies"
CustomerDetails.Tables(0).TableName = "Companies"
Dim CustomerTable As DataTable
Dim CustomerRow As DataRow
If CustomerDetails.Tables.Count > 0 Then
CustomerTable = CustomerDetails.Tables(0)
If CustomerTable.Rows.Count > 0 Then
Dim i As Integer
For i = 0 To CustomerTable.Rows.Count - 1
CustomerRow = CustomerTable.Rows(i)
Dim CC As New Customers
CC.Code = CustomerRow.Item("Code")
CC.Name = CustomerRow.Item("Name")
CC.InternalID = CustomerRow.Item("InternalID")
Cust.Add(CC)
Next i
' Serialize the results as JSON
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(Cust.GetType())
Dim Stream As MemoryStream = New MemoryStream
serializer.WriteObject(Stream, Cust)
' Return the results serialized as JSON
Dim json As String = Encoding.Default.GetString(Stream.ToArray())
Return New MemoryStream(Encoding.UTF8.GetBytes(json))
Obj.CloseConnection()
WebOperationContext.Current.OutgoingResponse.StatusCode = 200
WebOperationContext.Current.OutgoingResponse.StatusDescription = "OK"
End If
End If
Else
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Cust = Nothing
Return Nothing
End If
End If
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", ex.Message, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message
Return Nothing
End Try
Dispose()
End Function
How should my JSON output look like in my service in order to send out the correct callback? What should I do in order for this error not to show?

Request.Form() not working

I have a file intended to send data to server via Ajax, I've tried some libraries but I cant get them to work so I´m trying the simple Request.Form() method in the ASP server file, not working either.
the Ajax post:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://localhost/serv/sync.asp", true);
DataToSend = "id=1";
xmlhttp.addEventListener("load", function () {
if(xmlhttp.status === 200){
//event handler
};
}, false);
xmlhttp.send(DataToSend);
the ASP file:
<%#language=vbscript%>
<%
value = Request.Form("id")
Response.ContentType = "text/xml"
response.write (value)
%>
Wat's the problem with this? I've checked the Post in console and its working, but I can't catch the values on the server side.
The original idea was to send a Json string, parse it in the server and do the dataBase inserts, but couldn't get it to work, does anyone have a working snippet or a link to a working Json parsing method in Classic ASP?
Thanks.
Note: I've tried changing the server file to a different folder due to threading issues, and changing the URL to "http://127.0.0.1/serv/sync.asp".
I've used this with success:
JS:
if (window.XMLHttpRequest) {
httprequest = new XMLHttpRequest();
httprequest.texto = busca.id;
} else if(window.ActiveXObject) {
httprequest = new ActiveXObject("Microsoft.XMLHTTP");
httprequest.texto = busca.id;
} else {
alert("Seu navegador não suporta Ajax.");
return false;
}
if (httprequest.readyState == 4 || httprequest.readyState == 0) {
var busca = escape("texto texto texto");
httprequest.open("POST", "../busca_ajax.asp", true);
httprequest.onreadystatechange = retornaValores;
httprequest.send("busca=" + busca + "&teste=2");
}
function retornaValores() {
if (httprequest.readyState == 4) {
alert(httprequest.responseText);
}
}
ASP:
dim busca
busca = trim(request("busca"))
response.write busca
Edit:
if you can, I recommend you to use jQuery. It eases the process a lot:
$.ajax({
url: "lista.asp",
data: { 'ajax': 's', 'dados': '{"id": 123, "nome":"teste"}'},
cache: false,
dataType: "json",
success: function(dados) {
alert(dados);
},
error: function() {
alert("ERRO!");
}
});
ASP:
dim ajax, id
ajax = request.form("ajax")
dados = request.form("dados") ' this is a JSON string
response.write dados

Download File from C# through Web Method via Ajax call?

I have tried to download the file from the server through the webmethod
but it has not work for me.
my code as below
[System.Web.Services.WebMethod()]
public static string GetServerDateTime(string msg)
{
String result = "Result : " + DateTime.Now.ToString() + " - From Server";
System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["FolderPath"].ToString()) + "\\" + "Default.aspx");
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
//HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Flush();
Response.End();
return result;
}
and my ajax call code is as below
<script type="text/javascript">
function GetDateTime() {
var params = "{'msg':'From Client'}";
$.ajax
({
type: "POST",
url: "Default.aspx/GetServerDateTime",
data: params,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
},
error: function (err) {
}
});
}
</script>
and i have called this function in button click..
i don't know how to download the file with other methods
Please suggest me if any other methods available or give the correction in the same code.
Thanks to all..
A WebMethod does not have control of the current response stream, so this is not possible to do this way. At the time you call a web method from javascript, the response stream is already delivered to the client, and there is nothing you can do about it.
An option to do this is that the WebMethod generates the file as a physical file somewhere on the server, and then returns the url to the generated file to the calling javascript, which in turn uses window.open(...) to open it.
In stead of generating a physical file, you can call some GenerateFile.aspx that does about what you initially tried in your WebMethod, but do it in Page_Load, and call window.open('GenerateFile.aspx?msg=From Clent') from javascript.
Instead of calling a Web Method it would be a better idea to use a generic handler (.ashx file) and put your code for downloading the file in the ProcessRequest method of the handler.
This is Ajax Call
$(".Download").bind("click", function ()
{
var CommentId = $(this).attr("data-id");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TaskComment.aspx/DownloadDoc",
data: "{'id':'" + CommentId + "'}",
success: function (data) {
},
complete: function () {
}
});
});
Code Behind C#
[System.Web.Services.WebMethod]
public static string DownloadDoc(string id)
{
string jsonStringList = "";
try
{
int CommentId = Convert.ToInt32(id);
TaskManagemtEntities contextDB = new TaskManagementEntities();
var FileDetail = contextDB.tblFile.Where(x => x.CommentId == CommentId).FirstOrDefault();
string fileName = FileDetail.FileName;
System.IO.FileStream fs = null;
string path = HostingEnvironment.ApplicationPhysicalPath + "/PostFiles/" + fileName;
fs = System.IO.File.Open(path + fileName, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.End();
fs = null;
//jsonStringList = new JavaScriptSerializer().Serialize(PendingTasks);
}
catch (Exception ex)
{
}
return jsonStringList;
}

Resources