I'm using plupload, the JQuery UI implementation. I'm trying to pass additional parameters to the server, but I can't make it work. It should be pretty straightforward, the parameters are already set when the function is executed, so that should not be a problem. I've tried this:
function GetPlUploader(m)
{
$("#divOpplaster").plupload(
{
// General settings
runtimes: 'flash,html5,silverlight',
url: 'upload.php',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multipart: true,
multipart_params: [
{
'ordre': ordreibruk,
'mode': m}
],
// Specify what files to browse for
filters: [
{
title: "Bildefiler",
extensions: "jpg,gif,png,bmp"}
],
// Flash settings
flash_swf_url: 'plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: 'plupload/js/plupload.silverlight.xap',
init: {
FileUploaded: function(up, file, info)
{
// Called when a file has finished uploading
console.log('[FileUploaded] File:', file, "Info:", info);
}
}
});
console.log("Ordre: " + ordreibruk + ". Mode: " + m)
$("#divOpplaster").dialog(
{
autoOpen: false,
width: 650,
show: "fade",
hide: "fade"
})
$("#divOpplaster").dialog("open")
// Client side form validation
$('form').submit(function(e)
{
var uploader = $('#uploader').plupload('getUploader');
// Files in queue upload them first
if (uploader.files.length > 0)
{
// When all files are uploaded submit form
uploader.bind('StateChanged', function()
{
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed))
{
$('form')[0].submit();
}
});
uploader.start();
}
else
alert('Du må velge minst én fil for opplasting.');
return false;
});
}
I've also tried to add this in the $('form').submit section:
uploader.bind('BeforeUpload', function(up)
{
up.settings.multipart_params =
{
'ordre': ordreibruk,
'mode': m
};
});
But to no avail.
I'm sure I'm overlooking something really simple, but what?
Kind regards,
Anders
I must confess I use to put my parameters as query string parameters in the url :
during init : url: '/upload.aspx?id='+Id,
or later : upldr.settings.url = upldr.settings.url + '&token=' + myToken;
It works fine.
Hope this will help
Had the same issue. Stumbled upon this snippet that can easily translated into coffescript as well that works for my project. Allows you to pass multipart params after initialization (like in the case a field can change before the upload is hit)
var myUploader = $('#uploader').plupload('getUploader');
myUploader.bind('BeforeUpload', function(up, file) {
up.settings.multipart_params = {path : $("#path").val()};
});
Call it after you do your normal initialize and setup of $("#divOpplaster").plupload(...) (and set your ID appropriately to your uploader field, of course)
Related
i have an issue witch Multer and NestJS to upload file. I try to check if file already exist to return an error. it's working well but if i try to re-upload a file after that, i have infinite pending request. (if i remove the filter i have no problem but i overwrite the file)
here my controller code:
#UseGuards(JwtAuthGuard)
#UseGuards(RolesGuard)
#Role('SCENARISTE')
#Post('upload/sound')
#UseInterceptors(FileInterceptor('file', {
storage: diskStorage({
destination: 'files/sounds',
filename: function (req, file, callback) {
return callback(null, file.originalname);
}
}),
fileFilter: (req, file, callback) => {
if (existsSync(join('files/sounds', file.originalname))) {
return callback(new NotAcceptableException(ErrorType.FILE_ALREADY_EXIST), false);
} else {
return callback(null, true);
}
},
}))
uploadSound(#UploadedFile() file: Express.Multer.File) {
const fileReponse = {
originalname: file.originalname,
mimetype: file.mimetype,
filename: file.filename,
size: file.size,
destination: file.destination,
fieldname: file.fieldname,
path: file.path
};
return fileReponse;
}
thank in advance for your help
may be the first request not close/stop correctly ?
According to Multer's documantion, whenever you want to throw an error, you must call the callback by passing the first argument with an error, and leave the second argument or pass the false value.
Hence, try to change your code like this:
return callback(new NotAcceptableException(ErrorType.FILE_ALREADY_EXIST));
I'm trying to build a cordova based application using ionic.
In my application , there is a section which users can select images from our server and move them or do some actions on it(like zoom & rotate ...). At the end I want them to be able to share the result on our website and social medias. My problem is that how can I take a screen shot from the layout which they build it? I've already seen html2canvas library , but it has a problem with out source images that are saved on our server and does not take screen shot of them.
Install the following plugin to your project
cordova plugin add https://github.com/gitawego/cordova-screenshot.git
Add this service to your angular module
.service('$cordovaScreenshot', ['$q', function($q) {
return {
capture: function(filename, extension, quality) {
extension = extension || 'jpg';
quality = quality || '100';
var defer = $q.defer();
navigator.screenshot.save(function(error, res) {
if (error) {
console.error(error);
defer.reject(error);
} else {
console.log('screenshot saved in: ', res.filePath);
defer.resolve(res.filePath);
}
}, extension, quality, filename);
return defer.promise;
}
};
}]);
Than, you can simply add a button to take a screen shot with this service.
I have a nice example here for taking a screenshot and share it on Facebook:
//Take a picture
$cordovaScreenshot.capture()
.then(function(result) {
//on success you get the image url
//post on facebook (image & link can be null)
$cordovaSocialSharing
.shareViaFacebook("Text to post here...", result, "Link to share")
.then(function(result) {
//do something on post success or ignore it...
}, function(err) {
console.log("there was an error sharing!");
});
}, function(err) {
console.log("there was an error taking a a screenshot!");
});
Please note that this example uses the social sharing plugin by ngCordova:
http://ngcordova.com/docs/plugins/socialSharing/
file Screenshot.js to:
var formats = ['png','jpg'];
function Screenshot() {
}
Screenshot.prototype.save = function (callback,format,quality, filename) {
format = (format || 'png').toLowerCase();
filename = filename || 'screenshot_'+Math.round((+(new Date()) + Math.random()));
if(formats.indexOf(format) === -1){
return callback && callback(new Error('invalid format '+format));
}
quality = typeof(quality) !== 'number'?100:quality;
cordova.exec(function(res){
callback && callback(null,res);
}, function(error){
callback && callback(error);
}, "Screenshot", "saveScreenshot", [format, quality, filename]);
};
Screenshot.install = function () {
if (!window.plugins) {
window.plugins = {};
}
window.plugins.screenshot = new Screenshot();
return window.plugins.screenshot;
};
cordova.addConstructor(Screenshot.install);
This way I can make the call with the following code:
window.plugins.screenshot.save(function(error,res){
if(error){
alert(error);
}else{
alert('ok',res.filePath); //should be path/to/myScreenshot.jpg
}
},'jpg',50,'myScreenShot');
This worked perfectly on my Android smartphone.
I also added in res / xml / config.xml file:
<feature name="Screenshot">
<param name="android-package" value="org.apache.cordova.screenshot.Screenshot"/>
</feature>
In the AndroidManifest.xml file:
And added the java class in the following package: org.apache.cordova.screenshot.Screenshot
All these configurations have the information in the plugin.xml file of the plugin
The easiest way is to use this plugin:
com.darktalker.cordova.screenshot
I'm using Meteor's CollectionFS and trying to display image files that were uploaded to the server. The I've attached a reference to the file objects in another object, as such:
Entries.insert({
title: title,
caption: caption,
file: fsFile,
});
I call Entries.find({}) and return that to a template, which I use to iterate through the entries. I've tried <img src="file.url">, but that doesn't work.
It works fine if I call the images collection directly, Images.find({}), and iterate through the files, getting their urls with the file context this.url. Is there a similar way to do it using the references in the Entires objects?
Try something like this: (note I'm using the underscore package)
Template.image_queue.helpers({
images: function() {
return _.map(Images.find().fetch(), function(image) {
return image.url();
});
}
});
Asuming
Images = new FS.Collection("images", {
stores: [new FS.Store.FileSystem("images", {
path: "~/uploads"
})]
});
Images.allow({
insert: function (userId, party) {
return true;
},
update: function (userId, party) {
return true;
},
remove: function (userId, party) {
return true;
},
download: function (userId, party) {
return true;
}
});
If you haven't published and subscribed to your CFS file, file.url returns undefined. In this case you can get file url by following way:
/cfs/files/{cfs_collection_name}/{fs_file_id}
For example:
<img src="/cfs/files/images/{{ file._id }}">
I'm trying to use the method setMetadata, using the File plugin, but it seems does not work.
No Success or Fail callback is executed. When I use console.log(entry.setMetadata), it prints the correct method. I use the File plugin to access, create and delete files and folders without problems. Only the setMetadata doesn't work.
Example:
localFileSystem = LocalFileSystem.PERSISTENT;
subFolder = "Backups";
metadataKey = "com.apple.MobileBackup";
metadataValue = 1;
window.requestFileSystem(localFileSystem, 0, function(fileSystem) {
fileSystem.root.getDirectory(subFolder, {create: true, exclusive: false}, function(parent) {
var data = {};
data[metadataKey] = metadataValue;
console.log(data); // OK
console.log(parent); // OK
parent.setMetadata(function() {
console.log("success setting metadata"); // Nothing
}, function() {
console.log("error setting metadata"); // Nothing
}, data);
}, function() {
console.log("error getting dir"); // Nothing, directory is OK
});
}, function(error) {
console.log(error.code); // No error here
});
It was a bug on the File plugin. I checked with the developers on Github:
https://github.com/apache/cordova-plugin-file/pull/39
Just waiting for changes on the Phonegap site.
This is first time I am using a framework for development and stuck with the very first step.
I am converting a Flex application to Javascript application and using backbone as framework.
I have to load a text file which is in name value format.
<!doctype html>
<html>
<head>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js'></script>
<script>
var ResourceBundleCollection = Backbone.Collection.extend({
url:'ResourceBundle.txt',
});
var resourceBundleCollection = new ResourceBundleCollection();
resourceBundleCollection.fetch();
</script>
</head>
<body>
</body>
</html>
The ResourceBundle.txt includes the content in following format
location_icon=../../abc/test.png
right_nav_arrow_image=assets/images/arrow.png
right_nav_arrow_image_visible=true
It is throwing following error
not well-formed
I could load the text file easily using JQuery and parse it
$.ajax({
type : "GET",
url : "ResourceBundle.txt",
datatype : "script",
success : resourceXMLLoaded
});
and parse it using the following code
var lines = txt.split("\n");
for(var i=0;i<lines.length;i++) {
if(lines[i].length > 5) {
var _arr = lines[i].split("=");
resourceBundleObj[$.trim(_arr[0])] = $.trim(_arr[1]);
}
}
Please advice how to achieve the same results in backbone.js
If you MUST use plain text to support this, you can override Backbone.Collection.parse to achieve what you need.
In addition to that, you may also want to create a ResourceBundleModel to host each item in the ResourceBundleCollection.
You can see a demo here: http://jsfiddle.net/dashk/66nkF/
Code for Model & Collection is here:
// Define a Backbone.Model that host each ResourceBundle
var ResourceBundleModel = Backbone.Model.extend({
defaults: function() {
return {
name: null,
value: null
};
}
});
// Define a collection of ResourceBundleModels.
var ResourceBundleCollection = Backbone.Collection.extend({
// Each collection should know what Model it works with, though
// not mandated, I guess this is best practice.
model: ResourceBundleModel,
// Replace this with your URL - This is just so we can demo
// this in JSFiddle.
url: '/echo/html/',
parse: function(resp) {
// Once AJAX is completed, Backbone will call this function
// as a part of 'reset' to get a list of models based on
// XHR response.
var data = [];
var lines = resp.split("\n");
// I am just reusing your parsing logic here. :)
for (var i=0; i<lines.length; i++) {
if (lines[i].length > 5) {
var _arr = lines[i].split("=");
// Instead of putting this into collection directly,
// we will create new ResourceBundleModel to contain
// the data.
data.push(new ResourceBundleModel({
name: $.trim(_arr[0]),
value: $.trim(_arr[1])
}));
}
}
// Now, you've an array of ResourceBundleModel. This set of
// data will be used to construct ResourceBundleCollection.
return data;
},
// Override .sync so we can demo the feature on JSFiddle
sync: function(method, model, options) {
// When you do a .fetch, method is 'read'
if (method === 'read') {
var me = this;
// Make an XHR request to get data
// Replace this code with your own code
Backbone.ajax({
url: this.url,
method: 'POST',
data: {
// Feed mock data into JSFiddle's mock XHR response
html: $('#mockData').text()
},
success: function(resp) {
options.success(me, resp, options);
},
error: function() {
if (options.error) {
options.error();
}
}
});
}
else {
// Call the default sync method for other sync method
Backbone.Collection.prototype.sync.apply(this, arguments);
}
}
});
Backbone is designed to work with a RESTful API through JSON natively. It however is a library that is flexible enough to fit your need, given enough customization.
By default a collection in Backbone will only accept a JSON formatted collection.
So you need to convert your input to JSON format:
[{"name": "name", "value": "value},
{"name": "name", "value": "value}, ...
]
Of course you can override the default behaviour:
Overriding backbone's parse function