how does Valums-File-Uploader get fileSize in onComplete and pass it to server as params - filesize

I am using Valums-File-Uploader VERSION 2.1.2,It comes from https://github.com/Valums-File-Uploader/file-uploader.
Now, after uploading file successfully,I want to save file name and size to Sqlserver at once.
new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/ashx/FileHandler.ashx',
//filename: fileName, filesize: filesize,
params: { action: 'uploadfile', filename: fileName, filesize: filesize},------filesize from onComplete function
autoUpload: true,
extraDropzones: [qq.getByClass(document, 'qq-upload-extra-drop-area')[0]],
// Max file size limit
sizeLimit: 5200000,
// This function is executed once uploaded.
// This is appends the filenames to a div, but it could be anything!
onComplete: function (id, fileName, responseJSON) {
if (responseJSON.success) {
$('#uploaded_files').append('<br />uploaded: "' + fileName + '" ');
----------- how to set file size to a local variable filesize
}
msgShow(responseJSON.msg);
}})
how can I get fileSize from Valums-File-Uploader onComplete and pass it to server as params?
thanks a lot in advance for any help!

The onComplete callback is invoked after your server has already processed the file and has returned a response.
The repo you referenced was abandoned months ago. You should be using Widen/fine-uploader.

Related

Validate storage file data in Firebase cloud function

After uploading a file in Firebase storage I want to call a firebase cloud function from my web app which will validate the file data I sent to it, and then store it in the real-time database.
I am calling the function using the following code:
var fileRef = 'Files/' + user.uid + '/' + fileId + '/' + file.name;
var storage = firebase.storage().ref(fileRef);
//Upload the file
//..................
// After uploading the file
storage.getMetadata().then(function(metadata) {
var date = metadata.timeCreated.toString();
var storage = firebase.storage().ref('Files/' + user.uid + '/' + fileId + '/' + file.name);
storage.getDownloadURL().then(function(url){
var saveFileData = functions.httpsCallable('saveFileData');
saveFileData({
fileId: fileId,
fileRef: fileRef,
fileData: {
Uploader: user.uid,
Title: title,
FileName: file.name,
Size: fileSize,
DownloadURL: url,
UploadDate: date,
}
}).then(function(){
// Do something
});
});
});
I want to validate values of FileName, Size, DownloadURL and UploadDate in the cloud function based on the following conditions:
fileRef contains an existing file from the firebase storage.
FileName matches with the name of the file represented by fileRef.
Size matches with the size of the file represented by fileRef.
UploadDate matches with the creation date of the file represented by fileRef.
DownloadURL contains the download link of the file represented by fileRef.
What will be an appropriate way to do this from Firebase cloud function?
You can use storage triggers, Deploy in Firebase Cloud Functions,
In the object you will get all the metadata for the uploaded file as like here
exports.generateMetaForUpload = functions.storage
.object()
.onFinalize(object => {
console.log(object);
//do whatever you need to verify
});

docompress-zip in Node WebKit app cannot unzip downloaded file, downloaded file "corrupt" according to WinRAR

I'm attempting to write an automated installer for a *.exe file. I am using node-webkit, my unzipper is decompress-zip. I am downloading the installer via AJAX:
$.ajax({
type: "GET",
url: 'https://mywebste.com/SyncCtrl.zip',
contentType: "application/zip;",
success: function (dat) {
console.log(dat)
fs.writeFile("./SyncCtrl.zip", dat, function () {
console.log(dat)
})
},
error: function (err) {
console.log(err)
fs.writeFile("./SyncCtrl.zip", err.responseText, function () {
})
}
})
The .zip is written through the err.responseText content. I know this isn't best practice, but I haven't been able to get it into the success callback, even though the response code is 200. This is for another question though.
After I write the .zip file to disk, I wait for an authentication request, then unzip it in the success callback:
var unzip = new dc("./SyncCtrl.zip")
unzip.on('error', function (err) {
console.log("Something went terribly wrong.")
console.log(err)
})
unzip.on('extract', function (log) {
console.log("Finished!")
console.log(log)
})
unzip.on('progress', function (i, c) { //index, count (irrelevant for single file)
console.log("Extraction progress.")
})
unzip.extract({
path: "./SyncCtrl"
})
This is nearly copy/pasted directly from the decompress-zip github page. This fails, in the error handler it prints:
Error {message: "File entry unexpectedly large: 80606 (max: 4096)"}
I assume this limit is in MB? This is very confusing as in both locations the file size on disk is 1.7MB for the file I'm trying to extract. Any help is greatly appreciated.
The best way to accomplish this is to interpret the static file as a stream.
Simply using the static file on the server, this is my working node-webkit code:
var file = fs.createWriteStream("./MOCSyncCtrl.zip");
var request = https.get("https://moc.maps-adr.com/MOCSyncCtrl.zip", function (response) {
response.pipe(file);
});

rename file with django-ajax-uploader

I am using https://github.com/skoczen/django-ajax-uploader to upload a file in django. It works but I would like to rename the uploaded file during the process. I want to add a timestamp so I am sure it has a unique name.
How to do that?
I finally ended up using jQuery-File-Upload. It allows to define the path of the file inside the view.Example:
urls.py
url(r'^upload_question_photo/$', UploadQuestionPhoto.as_view(), name="upload_question_photo"),
index.html
var input=$(this).find("input");
var formData = new FormData();
formData.append('photo', input[0].files[0]);
formData.append('question', input.attr("name"));
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
input.fileupload(
{
dataType: 'json',
url: "{% url 'campaigns:upload_question_photo' %}",
formData: formData,
//the file has been successfully uploaded
done: function (e, data)
{
response=data.result;
window.console&&console.log("Successfully uploaded!");
window.console&&console.log(response.path);
}.bind(this),
processfail: function (e, data)
{
window.console&&console.log('Upload has failed');
}.bind(this)
});
views.py
class UploadQuestionPhoto(View):
u"""Uploads photos with ajax
Based on the code #https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
"""
def post(self, request, *args, **kwargs):
print "UploadQuestionPhoto post"
response={}
question=str(request.POST["question"])
#path where the file is going to be stored
path="/question/" + question + "/"
photo_path=settings.MEDIA_ROOT + path
# if 'f' query parameter is not specified -> file is being uploaded
if not ("f" in request.GET.keys()):
print "file upload"
# make sure some files have been uploaded
if request.FILES:
# get the uploaded file
photo_file = request.FILES["question_field_" + question]
name_with_timestamp=str(time.time()) + "_" + photo_file.name
# create directory if not exists already
if not os.path.exists(photo_path):
os.makedirs(photo_path)
# add timestamp to the file name to avoid conflicts of files with the same name
filename = os.path.join(photo_path, name_with_timestamp)
# open the file handler with write binary mode
destination = open(filename, "wb+")
# save file data with the chunk method in case the file is too big (save memory)
for chunk in photo_file.chunks():
destination.write(chunk)
destination.close()
#response sent back to ajax once the file has been successfuly uploaded
response['status']='success'
response["path"]=photo_path+name_with_timestamp
# file has to be deleted (TODO: NOT TESTED)
else:
# get the file path by getting it from the query (e.g. '?f=filename.here')
filepath = os.path.join(photo_path, request.GET["f"])
os.remove(filepath)
# generate true json result (if true is not returned, the file will not be removed from the upload queue)
response = True
# return the result data (json)
return HttpResponse(json.dumps(response), content_type="application/json")
VoilĂ  ! Hope it helps.

Ajax Express NodeJS to load ejs template in part of page

Ok, so I have code that brings me to my index page, then I am calling code through ajax to give me back results from my mongoose db. All of those calls are working, but I cannot seem to figure out how to get my code to execute on success of the ajax call to load another smaller ejs file in a portion of the current page? I have read a few things that say I need to render the ejs server side, but how to I make a call to the server and have it only update a part of the page and not do a whole page load. I am trying to execute a search function on a page that already yields the full results, so I want to replace the full results with what has been searched. Here are the export calls I have to the database:
exports.index = function(req, res, next){
Recipe.find().
sort('-updated_at').
exec(function(err, recipes, count){
if( err ) return next( err );
res.render('index', { title: 'Recipe Finder Index', recipes:recipes });
})
};
exports.search = function(req, res, next){
var param=req.params.search;
console.log(param);
Recipe.find({"fn":new RegExp(param)}).
sort('-updated_at').
exec(function(err, recipes, count){
if( err ) return next( err );
//res.render('index', { title: 'Recipe Finder Index', recipes:recipes });
res.contentType('json');
console.log(JSON.stringify({recipes:recipes}));
res.write(JSON.stringify({recipes:recipes}));
res.end();
})
};
So then I have this inside the first ejs file that loads in a script tag:
$('#submitSearch').click(function(){
console.log("clicked");
$.ajax({
url: '/ajax/'+$('input[name=search]').val()
, type: 'POST'
, cache: false
, complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
console.log(data);
console.log('process sucess');
//returns correct data, but then how can I call ejs?
},
});
So the code gives me the objects I am seeking, it grabs the data from the database, but I am having trouble locating code to have a portion of my site reload an ejs file with the new objects I have gotten back. I saw online that partials are no longer supported and I should be using include, but that looks like it only gives an ejs to a portion of the site, does not tell me how to render the ejs with the new data from ajax?

Passing the uploaded file path to controller action using uploadify

I'm using uploadify in my MVC3 project. It works fine to upload multiple files and saving to folders as well.
How to pass the path of the uploaded file to controller action ? -- I need to pass it to the ExtractingZip action of my controller.
To extract the contents of the .zip file, I'm using DotNetZip Library.
Here is what i've tried so far.
$('#file_upload').uploadify({
'checkExisting': 'Content/uploadify/check-exists.php',
'swf': '/Content/uploadify/uploadify.swf',
'uploader': '/Home/Index',
'auto': false,
'buttonText': 'Browse',
'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif;*.zip',
'removeCompleted': false,
'onSelect': function (file) {
if (file.type == ".zip") {
debugger;
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("ExtractingZip", "Home")',
data: ({ fileName: file.name}), // I dont see a file.path to pass it to controller
success: function (result) {
alert('Success');
},
error: function (result) {
alert('error');
}
});
}
}
});
Here is my controller action:
[HttpPost]
public ActionResult ExtractingZip(string fileName,string filePath, HttpPostedFileBase fileData)
{
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
var collections = zip1.SelectEntries("name=*.jpg;*.jpeg;*.png;*.gif;");
foreach (var item in collections)
{
item.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
return Json(true);
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileData)
{
foreach (var file in fileData)
{
if (file.ContentLength > 0)
{
string currpath;
currpath = Path.Combine(Server.MapPath("~/Images/User3"), file.FileName);
//save to a physical location
file.SaveAs(currpath);
}
}
}
You don't need to pass the zip's filepath when it's uploaded. The filepath would be from the clients machine right? Your application on your server has no knowledge or access to the clients file system.
The good news is you don't need it. You already have the contents of your file in memory. I have never used donetzip but some quick googling reveals that you can read zips directly from a stream.
Check out these links:
Cannot read zip file from HttpInputStream using DotNetZip 1.9
Extracting zip from stream with DotNetZip
So using those posts as a base to go off of... It looks like you should be able to change your code like so:
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
....
Changes to...
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(fileData.InputStream))
{
....
Let me know if that helps.
First of, due to security reasons you have no access directly to clients machine. While a user uploads some files, web browsers make one or tow (usually 1, according to RFC) stream and server-side script reads that stream, so do not waste your time to get files directly from user's local machine's filepath.
To extract archives (s.a: Zip, Rar) I highly recommend you to use SevenZipSharp. It works really good and easy with Streams and also many compression formats.
As they documentation you can extract stream like this:
using (MemoryStream msin = new MemoryStream(fileData.InputStream))
{ ... }

Resources