I used the "blobProperties -> name" property for the fine-uploader as stated in the following answer: https://stackoverflow.com/a/36453417/6746874
It is supposed to set the name for the uploaded file to the result from a function (if a function is set to this property).
So I created a function to get called, which calls a function from an asp.net controller where I create a GUID.
Here is a code example for my javascript code:
blobProperties: {//Set the names from the files to a server generated guid
name: function (fileId) {
return new Promise(function (resolve) {
// retrieve file name for this file from controller
$.ajax({
type: "GET",
url: "/controller/action",
headers: { "cache-control": "no-cache" },
success: function (result) {
uploader.setUuid(fileId, result);
resolve(result);
},
failure: function (error) {
alert("Failure")
}
});
})
}
}
It calls the action via ajax, and if successfull it sets the current files uuid and the name to the returned value.
This works great, but only if the file is not chunked.
If the file is chunked, the action gets called multiple times. And for every chunk a new Guid as a filename and uuid is created. So it gets into an invalid state, because when the fine-uploader tries to combine the chunks, azure returns an error-code:
400
With the message: The specified block list is invalid
My question is is this behaviour intentionally to call it for every chunk? If yes how could I prevent it from getting called multiple times per file?
P.S. In the linked answer is stated that it should only be called once
Related
I want a local file (on the server) to be downloaded by the user. The user first kicks off the file creation by pressing a button and once the file is ready, he should be able to clock on a link or a button to download the file.
Creating the file has not been a problem, as i simply send an AJAX call to my backend which looks like
#POST
#Path("/createFile")
#Produces("application/text")
#Consumes("application/json")
public String createFile(String argsFromPage) {
/*File creation code here*/
return "Path of file created";
}
Now, that the file is created, all I want is to create a link which the user can click and download this file. For now, the file can be either a binary or a CSV file. I have made several attempts but without any success
<button onclick='create_file()'>Create</button>
function create_file() {
$.ajax({
method : "POST",
url : ".path/to/backend/service",
contentType : "application/json",
data : JSON.stringify({
param1 : val1
})
}).done(function(data) {
console.log(data);
});
}
now once the file has been created, is it possible to create a download link? Better still, is it possible to invoke the download as soon as the file is created? Should this be done in the browser, or the back end?
Follow Up
Once the file has been downloaded, how can i delete it form the server? Is there any way to endure that the file download has been completed?
To create a link to the file you can just create an a element in the DOM within the done() handler. Try this:
function create_file() {
$.ajax({
method: "POST",
url: ".path/to/backend/service",
contentType: "application/json",
data: { param1: val1 } // I assume 'val1' is declared in a higher scope?
}).done(function(path) {
$('#someContainer').append('Click here to download');
});
}
Note that I removed the manual JSON.stringify call as jQuery will do this for you. Also note that it would be better to return JSON from the AJAX request as it avoids issues with whitespace, although the above should still work given the code sample you provided.
I have a collection that fetches with this line:
console.info("before fetching drivesCollection");
this.drivesCollection.fetch({
success: function() {
console.info("inside fetching drivesCollection");
},
error: function(collection, response, options) {
console.log('ERROR fetching drivesCollection ');
}
});
console.info("after fetching drivesCollection");
the fetching works as expected, and the error callback never get's called. I can see all models (200+) inside the collection afterwards. The problem is that anything inside the success function is not being called. I need to put a function there.
I tried to debug why the success function is being skipped somehow using the parse function of the collection definition as this:
parse: function(response){
console.log('starting parsing of drivesCollection');
console.log(response.length);
console.log(response);
return response
},
it works as expected, and returns valid values that are inserted into the collection...
Any ideas why my success function never runs?
Two things I think of is:
1) Your server isn't sending the right header information concerning content type in which the quick fix would be to force the use of getting JSON data by adding the parameter
this.drivesCollection.fetch({
dataType: 'json',
success: function() {
console.info("inside fetching drivesCollection");
}
});
2) OR, you're mistakenly are using a Backbone.Model to fetch collections and not a Backbone.Collection (I've made that mistake a few times)
I've been beating my head over this for quite a while now, so I think it's time I reach out for help. I have some already existing code that uses the jQuery File Uploader plugin, allowing me to upload files to my webserver. The trouble I am having is listing files that already exist on the web server.
Here is my initialization code that runs at the client:
$('#fileupload').fileupload({
disableImageResize: false,
url: '/api/upload',
done: function (e, data) { // data is checked here }
});
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0],
data: { action: "FileList", blob: "uts", path: "Unit 14/Binaries/" }
}).always(function (e, data) {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), { result: result });
});
Now, I am trying to return a list of pre-existing files on the server side that matches the JSON response akin to the documentation. My ASP.NET code on the server side is as follows (with two bogus files called "Something" and "SomethingElse" using my FilesStatus class).
// Get a list of files from
private void FileList(HttpContext hc)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<FilesStatus> fs_list = new List<FilesStatus>();
fs_list.Add(new FilesStatus("Something", 124));
fs_list.Add(new FilesStatus("SomethingElse", 124));
HttpContext.Current.Response.AddHeader("Pragma", "no-cache");
HttpContext.Current.Response.AddHeader("Cache-Control", "private, no-cache");
hc.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
var result = new { files = fs_list.ToArray() };
hc.Response.Write(serializer.Serialize(result));
hc.Response.ContentType = "application/json";
HttpContext.Current.Response.StatusCode = 200;
}
In the "done" function of the AJAX code, I see what I believe is the proper response on the client side. Here, you can see the format in my Javascript debugger (i.e., a top level "files" that is an array):
These files do not get populated in to the file list, though. The code that I marked "//data is checked here" in the main done() function shows that the array can be accessed as "data.result.files" NOT "data.files." I can change ".call(this, $.Event('done'), { result: result });" to ".call(this, $.Event('done'), { files: result.files });" so that "data.files" is the location of the file array, but this does not solve the problem. I can't seem to get any pre-existing files to load in to the list.
Does anyone see what I am doing wrong? Happy holidays.
What happens when you change the line:
hc.Response.Write(serializer.Serialize(result));
into
hc.Response.Write(serializer.Serialize(fs_list.ToArray()));
It looks like the serializer is taking the variable name into account when you are serializing your file descriptions. The 'result' JSON object should disappear from the response.
I was overwriting the done() method where I have:
done: function (e, data) { // data is checked here }
I did this for debugging, but apparently it blocks the pre-existing file list from being loaded and calling the download template.
I send a post to the server to create a new table entry in my database. Once the table entry is created I have the server respond with the id of the table entry. In the chrome developer tools I can see the response as just a singular number (i.e. if its the fifth entry in the table the server response is just 5). How do I store this information using javascript/YUI to be used later? Do I have to do something with the Y.io on: success function?
EDIT:
Y.io('/sessionsimulator/sessioncreate/', {
method: 'POST',
data: jdtoldstring,
headers: {
'Content-Type': 'application/json'
},
on: {
success: buildtable()
}
});
this is the code that posts the date/time and creates a session id. I can view the sqlite table afterwards and see that the session is created exactly how I wanted. the success function buildtable is the code that is called to generate the simulated data. within buildtable() i have a global variable that I am trying to set called sess_is
sess_id = Y.JSON.parse.responseText;
that statement lies within buildtable(), but when the table is created, the column that is filled with sess_id the variable is "undefined."
I can see in the developer tools the response to the url call /createsession is a number, I am just trying to pick that number and store it in sess_id variable.
If the response is just a number, you can access it from response.responseText in your IO success callback. It's a string, so you need to parse it as a number:
Y.io(url, {
//...
on: {
success: function (requestId, response) {
var id = parseInt(response.responseText, 10);
// do something with the id
}
}
});
It's usually a good idea to send JSON from the server and parse it in JavaScript when you want to send more information than just a number. You can read more about this in the IO User Guide, starting from the Response Object section.
In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!