ng-file-upload with multiple file upload and progress bar - ruby-on-rails

I want to upload multiple files to rails server and want to show separate progress bar for each files. I am using ng-file-upload to upload files. files are getting uploaded but it showing progress for only last file and not for others..I am attaching my code. please help.
Angular controller code:
$scope.upload_file = function() {
var files = $scope.files;
var uploadUrl = base_url+"/upload_image";
var job_id = $scope.directive.id;
if(current_user.role == "third_party_vendor" || current_user.role == "employee")
{
var source = current_user.user_login+"-"+current_user.role;
}
else
{
var source = $scope.dataObj.source["user_login"]+"-"+$scope.dataObj.source["role"];
}
if(job_id === "" || job_id === undefined || files === undefined || files === ""){
error_notification("Please select a job and a file.");
return;
}
hideLoader();
$("#upload_resume_queue").modal('show');
var formData = new Array();
formData['job_id'] = job_id;
formData['context'] = "inside_page";
formData['source'] = source;
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.log(file.name);
$scope.upload = $upload.upload({
url: uploadUrl,
data:{myObj: formData},
file: file,
}).progress(function(evt) {
//console.log('percent: ' +parseInt(100.0 * evt.loaded / evt.total));
file.progress = Math.round(evt.loaded * 100 / evt.total)
}).success(function(responseText) {
hideLoader();
try{
var response = responseText;
}catch(e){
error_notification("Invalid Excel file Imported.");
return;
}
if(response.status==='wrong_content_type')
error_notification("Please upload a valid file format.",0);
if(response.status==='job_application_present'){
$scope.duplicate = true;
$scope.jobID = job_id;
$scope.user_id = response.user_id;
$scope.application_id = response.application_id;
//showModal('#duplicate_application_modal');
error_notification("Job Application already present for this user and job.",0);
}
if(response.status==='invalid_email')
error_notification("The email in the resume is an invalid one.",0);
if(response.status==='success')
success_notification("The uploaded resume has been parsed.",0);
});
}
};
Html code:
<input type="file" class="required file_browse" ng-file-select="" ng-model="files" multiple />

I am not able test the following but, I think I found what is wrong.
In JavaScript variables are scoped to functions. So, in your for loop you change value of file in var file = files[i]; line. At the end, after for loop finished the value of file is the last file.
At some point .progress event is fired by ng-file-upload to notify you about progress (for one of the files). And you update the status, but, since file has the value of the last file, not the one you expected to be, the last file's status is being updated.
That's why only the last file updated. To solve, you need to access the correct file for each progress event. To do this, you can keep file variable using an anonymous function.
for (var i = 0; i < files.length; i++) {
(function(file) {
console.log(file.name);
$scope.upload = $upload.upload({
url: uploadUrl,
data:{myObj: formData},
file: file,
}).progress(function(evt) {
//console.log('percent: ' +parseInt(100.0 * evt.loaded / evt.total));
file.progress = Math.round(evt.loaded * 100 / evt.total)
}).success(function(responseText) {
// the other stuff
});
})(files[i])
}
In your code there may be other problems related to variable scopes and javascript event loop. For more information please take a look at this.

Related

asp.net mvc 5 sent email attachments are damaged

I am trying to send an email using the method described in this tutorial with a model structure form this tutorial and im partially successfull in doing so. The only issue I am having is the fact that files sent as attachments are damaged. I have tried to get it working in so many ways that I lost count. Obviously haven't been trying hard enough since I didn't find the answer, but decided to ask while I continue looking for an answer.
My controller action is as follows:
public async Task<ActionResult> Index( [Bind(Include = "column names..")] Contact contact, HttpPostedFileBase upload){
if (ModelState.IsValid && status)
{
var message = new MailMessage();
if (upload != null && upload.ContentLength > 0)
{
// 4MB -> 4000 * 1024
const int maxFileSize = 4096000;
if (upload.ContentLength < maxFileSize)
{
var document = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Document,
ContentType = upload.ContentType
};
var supportedTypes = new[] {"doc", "docx", "pdf", "jpg"};
var extension = System.IO.Path.GetExtension(document.FileName);
if (extension != null)
{
var fileExt = extension.Substring(1);
if (!supportedTypes.Contains(fileExt))
{
ModelState.AddModelError("document", "Wrong format");
return View();
}
//this is the line that sends damaged attachments,
//I believe I should be using document in some way (using reader bit below),
//but whatever I use the code complains or crashes.
message.Attachments.Add(new Attachment(upload.InputStream, Path.GetFileName(upload.FileName)));
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
document.Content = reader.ReadBytes(upload.ContentLength);
//message.Attachments.Add(new Attachment(document.Content, document.FileName));
}
contact.Files = new List<File> {document};
}
}else
{
ModelState.AddModelError("document", "File too big. Max 4MB.");
}
}
EDIT: A lot of times the code cannot find the file, how do I make sure I give it correct path each time?

On Change not working for second time

I'm Calling onchange function from HTML. It works as expected for the first time. But Second time, its not. Not even the debugger is getting hitted in the function.
HTML
#Html.TextBoxFor(m => m.Attachment.AttachmentFile, new { type = "file", onchange = "GetAttachmentFileName()", style = "display:none" })
JavaScript
function GetAttachmentFileName() {
$("#Filesize").hide();
if ($("#Attachment_AttachmentFile").val() != null && $("#Attachment_AttachmentFile").val() != "") {
var filename = $("#Attachment_AttachmentFile").val().split('\\').pop().replace(" ", "");
$("#Attachment_StorageName").val(filename);
$("#filename").val(filename);
$("#attachmentFileerror span").css("display", "none");
var fileSize=0;
var maxFileSize = 10240000 // 10MB -> 10000 * 1024
fileSize = $("#" + "Attachment_AttachmentFile")[0].files[0].size //size in kb
if(fileSize>maxFileSize){
$("#Filesize").html("Please choose file less than 10MB");
$("#Filesize").css("display", "block");
$('#filename').val('');
}
else{
$("#Filesize").css("display", "none");
}
}
else
$("#Attachment_StorageName").val("");
}
You may want to consider explicitly clearing out the contents of your file <input> when the file that was added was too large. This should reset the onchange() event so that it will trigger again (as it will only be triggered if the actual file name is different) :
if(fileSize>maxFileSize){
$("#Filesize").html("Please choose file less than 10MB");
$("#Filesize").css("display", "block");
$('#filename').val('');
$("#Attachment_AttachmentFile").val('')'
}

Get a list of pictures and upload them with CasperJS?

I need some help with my CasperJS script.
I don't know how can I get all my pictures as an array from the current folder.
And how to loop to insert each one in the correct input.
Mmmh, difficult to explain so there is my starting code.
I put comment where I have problem.
var casper = require('casper').create();
casper.start('http://imgchili.net/', function() {
// Get a list with all the picture from the current folder.
// For each picture, click this button.
this.mouseEvent('click', 'input.button1:nth-child(6)');
this.fillSelectors('form#upload_form', {
// Another loop here.
'.grey > input:nth-child(2)': /* First picture */,
'.grey > input:nth-child(4)': /* Second picture */,
'.grey > input:nth-child(6)': /* Third picture */
}, true);
casper.capture('captureTest.png');
});
// 8s can be too low if I have a lot of pictures!
casper.wait(8000, function() {
casper.capture('captureResult.png');
})
casper.then(function() {
this.echo(this.fetchText('textarea.input_field:nth-child(11)'));
})
casper.run();
EDIT:
Thanks it helps me a lot. But I have problem to loop the inputs.
var fs = require('fs'),
casper = require('casper').create(),
myImages = fs.list(fs.workingDirectory + '/img');
casper.start('http://imgchili.net/', function() {
// For each image, click to add a new upload input.
// Begin with 2 because 0 = "."" and 1 = "..".
for (var i = 2; i < myImages.length; i++) {
this.mouseEvent('click', 'input.button1:nth-child(6)');
}
// It doesn't work and show no error...
for (var i = 2; i < myImages.length; i++) {
j = i*2;
input = '.grey > input:nth-child(' + j + ')';
this.fillSelectors('form#upload_form', {
input : '/img/' + myImages[i],
}, false);
// Even this part doesn't work
console.log('i = ' + i + ' & imgName = ' + myImages[i]);
}
});
casper.then(function() {
casper.capture('result.png');
});
casper.run();
You can use PhantomJS file system to get your current folder files. Here is the API Documentation.
The following gets your current folders files, and then filters all .png's into a new array. You can then use a loop to click the button for each image. You will have to alter / add your own code because this does not accomplish the upload task. This will should help you though.
// vars
var fs = require('fs'); // reference to phantomJS file system
var myFolder = fs.list(fs.workingDirectory); // gets all files in current folder
var myImages = []; // only images from current folder
var url = 'http://imgchili.net/'; // starting url
var fileType = '.png'; // image file type to filter by
casper.then(function() {
// create array of just images
for (var i = 0; i < myFolder.length; i++) {
if (myFolder[i].indexOf(fileType) != -1) {
myImages.push(myFolder[i]);
}
}
// click for each image
for (i = 0; i < myImages.length; i++) {
this.mouseEvent('click', 'input.button1:nth-child(6)');
}
});
// wait for images to be uploaded
// set timeout or defaults to caspers step timeout
casper.waitForSelector('#page_body', function() {
casper.capture('captureResult.png');
}, 15000);

nicUpload says "Invalid Upload ID", cant make it works

Im trying to implement nicEdit with the nicupload plugin, but when I select a file to upload it says "Failed to upload image", and the server response says "Invalid Upload ID".
This is the code that calls the script and initializes:
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">//<![CDATA[
bkLib.onDomLoaded(function() {
new nicEditor({uploadURI : '../../nicedit/nicUpload.php'}).panelInstance('area1');
});
//]]>
</script>
The path to nicUpload.php is correct, and the code is the one that can be found in the documentation: http://nicedit.com/src/nicUpload/nicUpload.js
I made the upload folder changes, and set write permissions. According to the documentation (http://wiki.nicedit.com/w/page/515/Configuration%20Options), thats all, but i keep getting errors. Any ideas?
After looking for an solution a long time (lot of posts without real solution), i now fixed the code myself. I'm now able to upload an image to my own server. Thx to firebug and eclipse ;-)
The main problem is that the nicUpload.php is old and not working with the current nicEdit-Upload function.
Missing is the error handling, feel free to add this...
Add the nicEditor to your php file and configure it to use the nicEdit.php:
new nicEditor({iconsPath : 'pics/nicEditorIcons.gif', uploadURI : 'script/nicUpload.php'}
Download the nicEdit.js uncompressed and change the following lines in nicEdit.js:
uploadFile : function() {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
this.onError("Only image files can be uploaded");
return;
}
this.fileInput.setStyle({ display: 'none' });
this.setProgress(0);
var fd = new FormData();
fd.append("image", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660");
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);
xhr.onload = function() {
try {
var res = JSON.parse(xhr.responseText);
} catch(e) {
return this.onError();
}
//this.onUploaded(res.upload); // CHANGE HERE
this.onUploaded(res);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
},
onUploaded : function(options) {
this.removePane();
//var src = options.links.original; // CHANGE HERE
var src = options['url'];
if(!this.im) {
this.ne.selectedInstance.restoreRng();
//var tmp = 'javascript:nicImTemp();';
this.ne.nicCommand("insertImage", src);
this.im = this.findElm('IMG','src', src);
}
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width'));
if(this.im) {
this.im.setAttributes({
src : src,
width : (w && options.image.width) ? Math.min(w, options.image.width) : ''
});
}
}
Change the nicUpload.php like this
<?php
/* NicEdit - Micro Inline WYSIWYG
* Copyright 2007-2009 Brian Kirchoff
*
* NicEdit is distributed under the terms of the MIT license
* For more information visit http://nicedit.com/
* Do not remove this copyright message
*
* nicUpload Reciever Script PHP Edition
* #description: Save images uploaded for a users computer to a directory, and
* return the URL of the image to the client for use in nicEdit
* #author: Brian Kirchoff <briankircho#gmail.com>
* #sponsored by: DotConcepts (http://www.dotconcepts.net)
* #version: 0.9.0
*/
/*
* #author: Christoph Pahre
* #version: 0.1
* #description: different modification, so that this php file is working with the newest nicEdit.js (needs also modification - #see)
* #see http://stackoverflow.com/questions/11677128/nicupload-says-invalid-upload-id-cant-make-it-works
*/
define('NICUPLOAD_PATH', '../images/uploadedImages'); // Set the path (relative or absolute) to
// the directory to save image files
define('NICUPLOAD_URI', '../images/uploadedImages'); // Set the URL (relative or absolute) to
// the directory defined above
$nicupload_allowed_extensions = array('jpg','jpeg','png','gif','bmp');
if(!function_exists('json_encode')) {
die('{"error" : "Image upload host does not have the required dependicies (json_encode/decode)"}');
}
if($_SERVER['REQUEST_METHOD']=='POST') { // Upload is complete
$file = $_FILES['image'];
$image = $file['tmp_name'];
$id = $file['name'];
$max_upload_size = ini_max_upload_size();
if(!$file) {
nicupload_error('Must be less than '.bytes_to_readable($max_upload_size));
}
$ext = strtolower(substr(strrchr($file['name'], '.'), 1));
#$size = getimagesize($image);
if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
nicupload_error('Invalid image file, must be a valid image less than '.bytes_to_readable($max_upload_size));
}
$filename = $id;
$path = NICUPLOAD_PATH.'/'.$filename;
if(!move_uploaded_file($image, $path)) {
nicupload_error('Server error, failed to move file');
}
$status = array();
$status['done'] = 1;
$status['width'] = $size[0];
$rp = realpath($path);
$status['url'] = NICUPLOAD_URI ."/".$id;
nicupload_output($status, false);
exit;
}
// UTILITY FUNCTIONS
function nicupload_error($msg) {
echo nicupload_output(array('error' => $msg));
}
function nicupload_output($status, $showLoadingMsg = false) {
$script = json_encode($status);
$script = str_replace("\\/", '/', $script);
echo $script;
exit;
}
function ini_max_upload_size() {
$post_size = ini_get('post_max_size');
$upload_size = ini_get('upload_max_filesize');
if(!$post_size) $post_size = '8M';
if(!$upload_size) $upload_size = '2M';
return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}
function ini_bytes_from_string($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
function bytes_to_readable( $bytes ) {
if ($bytes<=0)
return '0 Byte';
$convention=1000; //[1000->10^x|1024->2^x]
$s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
$e=floor(log($bytes,$convention));
return round($bytes/pow($convention,$e),2).' '.$s[$e];
}
?>
You can manually pass an id to your script: e.g nicUpload.php?id=introPicHeader and it will become introPicHeader.jpg (or appropriate extension) in the images folder you defined.
However, I have noticed that this script is broken and cannot access the configuration option uploadURI if specified directly in nicEdit.js during the nicEditorAdvancedButton.extend({. This causes access to an relatively pathed "Unknown" resource, causing an error.
The documentation implies otherwise and the fact that the nicURI was specified here for imgur.com (maybe as a default) gave me the impression I could also add a uploadURI reference to the nicUpload.php script in a single place rather than on every editor instantiation.
Update
This works if you pass it during instantiation, which I guess does allow for easy dynamic id population.
Unfortunately, the nicUpload.php is riddled with errors and it's output is not JSON. The editor expects to parse JSON and finds a script tag and errors with unexpected token "<".
There are a raft of other errors which I will attempt to identify:
In nicEdit.js
A.append("image") should be infact A.append("nicImage")
this.onUploaded(D.upload) should become this.onUploaded(D)
this.onUploaded(D) should be moved to within the try block after var D=JSON.parse(C.responseText) to fix variable scope issues
B.image.width needs to become B.width
In nicUpload.php
JSON output is not formed correctly, comment out html output and output just json_encode($status).
JSON output needs to return a key/value pair named links rather than url although renaming the var D=B.links to var D=B.url in nicEdit.js would also suffice as a fix.
Both php and javascript code leaves a lot to be desired, I get many errors regularly and have been fixing them myself.

Youtube video download URL

I wrote a program that gets youtube video URL and downloads it
Up today I did this:
1. get video "token" from "/get_video_info?video_id=ID" like:
http://www.youtube.com/get_video_info?video_id=jN0nWjvzeNc
2. Download Video by requesting it from "/get_video?video_id=ID&t=TOKEN&fmt=FORMAT_ID" like:
http://www.youtube.com/get_video?video_id=jN0nWjvzeNc&t=vjVQa1PpcFMgAK0HB1VRbinpVOwm29eGugPh3fBi6Dg%3D&fmt=18
But this doesn't work anymore!
What is the new download URL?
Thanks
Actually I'm working on the similar project that downloading the video file from youtube. I find that the get_video might be blocked by Youtube. so instead of using get_video., I use the video info retrieved from get_video_info and extract it to get the video file url.
Within the get_video_info, there are url_encoded_fmt_stream_map. After encoding it, you can find url and signature value of every video with different format. So the file url is like [url value]+'&signature='+[sig value].
Additionally I find the following topic that using same method with mine. Hope it can help you.
Can't Download from youtube
If you are interested about how to downloading youtube video file, there is a small program written by me to demonstrate the process. You are free to use it.
https://github.com/johnny0614/YoutubeVideoDownload
Add &asv=2 to the end of the URL.
You can get the stream directly by using only
http://www.youtube.com/get_video_info?video_id=jN0nWjvzeNc
I made a little script to stream youtube videos in PHP. See how the script get the video file.
<?php
#set_time_limit(0);
$id = $_GET['id']; //The youtube video ID
$type = $_GET['type']; //the MIME type of the video
parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id),$info);
$streams = explode(',',$info['url_encoded_fmt_stream_map']);
foreach($streams as $stream){
parse_str($stream,$real_stream);
$stype = $real_stream['type'];
if(strpos($real_stream['type'],';') !== false){
$tmp = explode(';',$real_stream['type']);
$stype = $tmp[0];
unset($tmp);
}
if($stype == $type && ($real_stream['quality'] == 'large' || $real_stream['quality'] == 'medium' || $real_stream['quality'] == 'small')){
header('Content-type: '.$stype);
header('Transfer-encoding: chunked');
#readfile($real_stream['url'].'&signature='.$real_stream['sig']); //Change here to do other things such as save the file to the filesystem etc.
ob_flush();
flush();
break;
}
}
?>
See the working demo here. I hope this can help you.
After a lot of failed tries, this github repositories help me:
https://github.com/rg3/youtube-dl
Get the url only like:
youtube-dl 'https://www.youtube.com/watch?v=bo_efYhYU2A' --get-url
download an mp4 and save as a.mp4 like:
youtube-dl 'https://www.youtube.com/watch?v=bo_efYhYU2A' -f mp4 -o a.mp4
Good luck.
Last time I was working on fixing one of the broken Chrome extensions to download YouTube video. I fixed it by altering the script part.
(Javascript)
var links = new String();
var downlink = new String();
var has22 = new Boolean();
has22 = false;
var Marked = false;
var FMT_DATA = fmt_url_map;//This is html text that you have to grab. In case of extension it was readily available through:document.getElementsByTagName('script');
var StrSplitter1 = '%2C', StrSplitter2 = '%26', StrSplitter3 = '%3D';
if (FMT_DATA.indexOf(',') > -1) { //Found ,
StrSplitter1 = ',';
StrSplitter2 = (FMT_DATA.indexOf('&') > -1) ? '&' : '\\u0026';
StrSplitter3 = '=';
}
var videoURL = new Array();
var FMT_DATA_PACKET = new Array();
var FMT_DATA_PACKET = FMT_DATA.split(StrSplitter1);
for (var i = 0; i < FMT_DATA_PACKET.length; i++) {
var FMT_DATA_FRAME = FMT_DATA_PACKET[i].split(StrSplitter2);
var FMT_DATA_DUEO = new Array();
for (var j = 0; j < FMT_DATA_FRAME.length; j++) {
var pair = FMT_DATA_FRAME[j].split(StrSplitter3);
if (pair.length == 2) {
FMT_DATA_DUEO[pair[0]] = pair[1];
}
}
var url = (FMT_DATA_DUEO['url']) ? FMT_DATA_DUEO['url'] : null;
if (url == null) continue;
url = unescape(unescape(url)).replace(/\\\//g, '/').replace(/\\u0026/g, '&');
var itag = (FMT_DATA_DUEO['itag']) ? FMT_DATA_DUEO['itag'] : null;
var itag = (FMT_DATA_DUEO['itag']) ? FMT_DATA_DUEO['itag'] : null;
if (itag == null) continue;
var signature = (FMT_DATA_DUEO['sig']) ? FMT_DATA_DUEO['sig'] : null;
if (signature != null) {
url = url + "&signature=" + signature;
}
if (url.toLowerCase().indexOf('http') == 0) { // validate URL
if (itag == '5') {
links += '<span class="yt-uix-button-menu-item" id="v240p">FLV (240p)</span>';
}
if (itag == '18') {
links += '<span class="yt-uix-button-menu-item" id="v360p">MP4 (360p)</span>';
}
if (itag == '35') {
links += '<span class="yt-uix-button-menu-item" id="v480p">FLV (480p)</span>';
}
if (itag == '22') {
links += '<span class="yt-uix-button-menu-item" id="v720p">MP4 HD (720p)</span>';
}
if (itag == '37') {
links += ' <span class="yt-uix-button-menu-item" id="v1080p">MP4 HD (1080p)</span>';
}
if (itag == '38') {
links += '<span class="yt-uix-button-menu-item" id="v4k">MP4 HD (4K)</span>';
}
FavVideo();
videoURL[itag] = url;
console.log(itag);
}
}
You can get separate video link from videoURL[itag] array.
The extension can be downloaded from here.
I hope this would help someone. This is working solution (as of 06-Apr-2013)

Resources