ASPupload 'if Not File Is Nothing' always returns false - asp-classic

Using Persits ASPupload component to upload and process files (Classic ASP).
The file is being uploaded via a jQuery ajax form.
I have run into an odd situation, where the customary test if Not File Is Nothing Then always returns false even when the file has most definitely been uploaded (I can see it on the server).
This is my jQuery code:
var hiddenSignature = $("#hiddenSignature").val();
var formData = new FormData();
formData.append('closingPic', $('#closingPic')[0].files[0]);
formData.append('hiddenSignature',hiddenSignature);
$.ajax({
url: "ajax_tickets_file.asp?action=cost",
type: "POST",
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: formData,
beforeSend: function() {
...
},
success: function(msg) {
...
}
});
And this is the server side code on ajax_tickets_file.asp:
Set objUpload = Server.CreateObject("Persits.Upload.1")
With objUpload
.CodePage = 65001
.OverwriteFiles = False
Set file = .Files("closingPic")
.SaveVirtual defaultUploadsFolder // a file is indeed saved on the server, at the correct location
response.write " saved "
if Not file Is Nothing Then
response.write “we have a file”
else
response.write "no file" // this is what I get
end if
So, as mentioned earlier, I get “no file” printed.
How could this happen?
Thanks

H/T to the owner of Persits ASPupload for helping me
Code should be:
.CodePage = 65001
.OverwriteFiles = False
//these 2 lines should be in reversed order: 'save' before 'set file'
.SaveVirtual defaultUploadsFolder
Set file = .Files("closingPic")

Related

Why server.mapPath is Invalid report file path in production but local machine is valid?

i spend a lot of time to resolve this problem but to working. I use server.mapPath function to specific valid path file. why only local machine is working but not working in production because i this (server.mapPath) is a great function
c#
[WebMethod]
public string getDocument(string id, string location)
{
ReportDocument report = new ReportDocument();
report.Load(Server.MapPath("~/Reports/report1.rpt"));
Stream stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
MemoryStream streamReader = new MemoryStream();
stream.CopyTo(streamReader);
return Convert.ToBase64String(streamReader.ToArray());
}
ajax
function printPreview(reqID) {
var base_url = "/Webservice/webService.asmx/getDocument";
$.ajax({
type: "POST",
url: base_url,
data: "{'id': " + reqID + ", 'location':'" + objUser.location + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d)
},
error: function (response) {
alert(response.d);
}
});
Check API backend
Look like the problem happen when ReportDocument.Load because i test in production with File.Exists function without ReportDocument.Load and the result return file is exist but cannot load why ? Have any one else know this ?
error exception
Could not load file or assembly 'CrystalDecisions.CrystalReports.Engine, Version=13.0.3500.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.
I'm add bindingRedirect from 13.0.2000.0 -> 13.0.3500.0 in web.config and still not working. I'm see in server production C:/Windows/assembly all of (CrystalDecisions.Shared, CrystalDecisions.CrystalReports.Engine, CrystalDecisions.ReportSource) is version 13.0.2000.0 but why another project is working. Please help me, thank you so much.
Try without the tilde and forward slash character.
report.Load(Server.MapPath("Reports/report1.rpt"));
This expects report (.rpt file) to be available in 'Reports' subfolder of your application root folder
You could use System.IO Path.Combine. There you just add your Foldernames and your Filename and get a correctly formatted Path. Could look something like that:
string sPath = Path.Combine(#"\\" + "Reports", "report1.rpt");
You can add string variables (Foldernames) with just a comma.

export excel from extjs grid

I want to export extjs grid content to excel file. So what i have done already:
i send to the servlet json content of the grid through Ext.Ajax.request, like
Ext.Ajax.request({
url : 'ExportToExcel',
method:'POST',
jsonData: this.store.proxy.reader.rawData,
scope : this,
success : function(response,options) {
this.onExportSuccess(response, options);
},
//method to call when the request is a failure
failure: function(response, options){
alert("FAILURE: " + response.statusText);
}
});
Then in servlet i get json in servlet do some stuff, e.g. create excel file, convert it to bytes array and try to put into response.
In Ext.Ajax.request in success method when i try to do something like this:
var blob = new Blob([response.responseText], { type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet});
var downloadUrl = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
it downloads excel file, but when i open it error occurs, saying format or extension is invalid.
WHY??
Whether it may depend on the encoding?
What i'm doing wrong?
Ext comes with an excel exporter built in. You may want to try using that to see if you get the desired results
grid.saveDocumentAs({
type: 'excel',
title: 'My Excel Title',
fileName: 'MyExcelFileName.xml'
});
From the toolkit : Ext.grid.plugin.Exporter

AJAX Callback using POST method

I require some assistance. I am using jQuery to cause an ajax callback:
function TestingCallback(controlId) {
if (controlId == 'drpControl') {
var options = {
type: "POST",
url: "Main.aspx",
data: { drpControl: $(".drpControl").val() },
//contentType: "application/json; charset=utf-8",
//cache: false,
success: function (data) {
},
complete: function (jqXHR, status) {
formData = $("#form1").serialize();
window.location = "Main.aspx?" + formData;
ShowLoadingBar();
return false;
}
};
var resp = $.ajax(options);
}
}
And the backend I get the data like so:
Request.Form["drpControl"], which works well.
But as soon as I add this line to the callback options : contentType: "application/json; charset=utf-8",, I get a value of null for Request.Form["drpControl"].
Please assist on how to overcome this.
Thanks in advance
Might I just add that I am trying to cause a postback but keep all control values, hence this line :
formData = $("#form1").serialize();
window.location = "Main.aspx?" + formData;
But after a second postback (on change of drpControl) field values gets cleared, I am assuming this has to do with IE not being able to cater for a long querystring, I have tested it in Chrome and it works perfect, but not IE, and I need it to work for IE 8.Any suggestions?
in content type just add this
contentType: "application/json"
Designating the encoding is somewhat redundant for JSON, since the default encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')-
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
Note sure but pass data like this
data: "{'drpControl' : " + $(".drpControl").val()+ "}",

How to catch every exception thrown in a webmethod but without those exceptions interrupting the execution of the program

Is there any way I can make that every exception thrown inside a webmethod go straight to the jQuery Ajax error callback function?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MantenimientoNotasCapacidades.aspx/SaveViaWebService",
data: JSON.stringify(params),
dataType: "json",
async: true,
success: function (data) {
},
error: function (request, status, error) {
var response = JSON.parse(request.responseText).d;
var error = JSON.parse(response);
alert(JSON.parse(request.responseText).error.message);
}
});
I know that using JSON.parse(request.responseText).Message should be enough to show the information for that error but all I've got now is that every time an exception is raised the code stops right there , being necessary to keep pressing F10 or F5 to finally be able to see the alert.
I already tried enclosing my code in a 'try' block but I don't see much point in doing that since I can't do much in the 'catch' block as I'd do in a visual basic application where I could use the 'catch' block to show the exception message in a MsgBox.
Is there any way to catch in the error callback function all the exceptions thrown in a webmethod but without them stopping the execution of the code?
Any help would be much appreciated.
P.S. Happy new year!!
Following #cmd.promt's advice, I changed the Response.StatusCode to 500 and created and object(myError) containing the description for the exception that was thrown, then the only thing left to do was to serialize the object and send it back to the client (Here I tried to use Response..Write("{""message"": ""action failed!""}") but for some reason I always ended up getting the same error : "JSON.parse: unexpected non-whitespace character after JSON data" so in the end I decided to go with json.net and forget all about response.Write)
<WebMethod()> _
Public Shared Function SaveViaWebService(lst As List(Of Students)) As String
Try
Catch ex As Exception
Dim httpResponse = HttpContext.Current.Response
httpResponse.Clear()
httpResponse.StatusCode = 500
'I thought that .StatusDescription would be useful but it turned out it didn't
'httpResponse.StatusDescription = ex.Message
Dim myError= New With {.message = ex.Message, .source = ex.Source}
Return JsonConvert.SerializeObject(myError)
End Try
End Function
And with that, the error is correctly sent to the error callback , where the only thing I had to do was to play with firebug and see how the error has been sent
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MantenimientoNotasCapacidades.aspx/SaveViaWebService",
data: JSON.stringify(params),
dataType: "json",
async: true,
success: function (data) {
},
error: function (request, status, error) {
var response = JSON.parse(request.responseText).d;
var error = JSON.parse(response);
alert(JSON.parse(request.responseText).error.message);
}
});
Thus far, everything is as I as wanted it , except for the exceptions that keep on interrupting the execution of the program. Is that their normal behaviour ?? Aren't they all supposed to go directly to the 'catch' block??

Dojo iframe load is not called

Im uplaoding file to Amazon S3 using dojo.io.iframe.send:
var d = dojo.io.iframe.send ({
url: url,
contentType: "multipart/form-data",
method: "POST",
form: this._form.domNode,
handleAs: "text",
load: dojo.hitch(this, function (respText) {
alert(1)
this.showLoading(false);
this.onSuccess(this.nodeFormName.value);
}),
error: dojo.hitch(this, function (err) {
console.log("err", err)
this.showError(err);
})
}, true);
I can see via using sniffer that file upload finished (and file is indeed in S3 bucket) but "load" or "error" callback functions are never called. Via sniffer I can see that response code is 204 "no content" and I assume that it may be root of the problem. Anyone had similar problem or know how to solve it?
Found solution. Since the only way for iframe to process result is to get format, I added redirect header for successfull upload on Amazon S3. Redirecting now to static page in format success
Did the trick.

Resources