How can i generate a blob url? - angularjs

I have a function that will determine if the gif is animated or non-animated. Everything is working fine, until i upload those gif to the server, and load it, the blob url is a empty string. How can i generate a blob url for this?
Due to the blob url being empty string, i get parameter 1 is not of type 'blob'
The function below determines if the gif is animated or not.
$scope.isNotAnimatedGIF = function(file) {
var reader = new FileReader();
return new Promise(function(resolve, reject) {
reader.onload = function (e) {
var gifInfo = gify.getInfo(reader.result);
if (gifInfo.images.length <= 1) {
file.animatedGIF = false;
resolve(true);
} else {
file.animatedGIF = true;
resolve(false);
}
}
reader.readAsArrayBuffer(file);
});
}
I am using Angular 1.4.10
Thank you !

You can use URL.createObjectURL() to create Blob url.
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
DEMO
function createbloburl(file, type) {
var blob = new Blob([file], {
type: type || 'application/*'
});
file = window.URL.createObjectURL(blob);
return file;
}
document.querySelector('#file').addEventListener('change', function(e) {
var file = e.currentTarget.files[0];
if (file) {
file = createbloburl(file, file.type);
document.querySelector('iframe').src = file;
//console.log(file)
}
})
<input id="file" type="file">
<iframe src=""></iframe>

try this reader.readAsDataURL(Blob|File).
you can find more from here

Related

How to handle download return File Result from controller ? MVC

I am not able to download file result in js. I am returning File Result to the js but dont know how to download it
To be short and specific i am returning word document from controller to js in which i need to download it and handle it in js.
My js method in which i am calling method and file result is returning to.
vm.establishmentAllRecord = function (page) {
if (page != undefined) {
vm.page = page;
}
var searchCriteria = {
From: vm.From,
To: vm.To,
Region: vm.SelectedRegion
}
surveyService.establishmentAllRecord(searchCriteria, (vm.page * vm.pagesize), vm.pagesize, vm.sortBy, vm.sortingDirection).then(function (d) {
var result = JSON.parse(d.data.data);
???
});
I need to ask how can i handle return File Result from controller on ??? this place and download
Hopes for your suggestions
EDITED:
i have return file system from controller is in this way,
FileResult result1 = PrintSurveyDetailsReport(VisitId);
return result1;
result1 contains 'ContentType="application/octet-stream"' , "FileContents" and "FileDownloadName"
Use the following function
var downloadFile = function (data, fileName, contentType) {
contentType = contentType || "application/octet-stream";
var blobObject = new Blob([data], {type: contentType});
try {
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}
catch (exp) {
var link = document.createElement('a');
link.setAttribute('href', URL.createObjectURL(blobObject));
link.setAttribute('download', fileName);
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link);
}
};

Getting files from google drive and display on my webpage via HTML5 input tag

I am facing a issue whereby my android users are unable to upload video files from their google drive to the website (when will upload file via input tag, you get the option to retrieve the file from google drive). What i found out so far is that if i send a partial files into readAsArrayBuffer (FileReader API) it wont work, it will only work if i use the whole file.
The reason i am passing a partial files is to handle the case of latency issue. I am using AngularJS. I am unable to share the code as its against my company policy.
UPDATE: Ytd, i ran FileReader.onerror it return this error:
DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.`
I am able to upload the files on Firefox and not Chrome.
Thank you
$scope.rewriteVideoFile = function(file, out) {
var totalBytes = 1750000;
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function() {
//Logic here
}
reader.readAsArrayBuffer(file.slice(0, totalBytes));
// reader.readAsArrayBuffer(file); this will work
});
};
function createVideoBlob(file) {
var maxSize = 1550000;
var sendSize = Math.min(maxSize, file.size);
return new Promise(function(resolve, reject) {
if (file.size <= maxSize) {
return resolve(file);
} else if (file.type === 'video/quicktime' || file.type === 'video/mp4') {
var out = [];
scope.rewriteVideoFile(file, out).then(function () {
console.log('rewriteVideoFile .then');
var blob = new Blob(out, {type : 'application/octet-stream'});
return resolve(blob);
});
} else {
return resolve(file.slice(0, sendSize, 'application/octet-stream'));
}
})
}

angularjs $http response data as readStream to Aliyun OSS?

I want to download an image file through XHR using the $http service provided by angularJS, and upload the response data (image data) to OSS(it is a service that host files provided by Alibaba) and it's api reference for put is:
which indicates that it will take a {String|Buffer|ReadStream} as the second parameter file,
but how can I transfer the response data so that I could make that a parameter for this put(name, file) method like:
$http.get("http://image.url/file.gif").then(
function success(response){
console.log("type of response.data is :" + typeof response.data);
oss.put("test.jpg", response.data); //<-- here will give an error
},
function fail(response){
console.log("error");
}
)
this will give a type error:
Any suggestion or answer is appreciated.
if you're getting the images via links all the time and you want to get the string data out of it, I've tried a small function that i hope it helps, it takes the link and puts to you the image data in base64 string format
function getBase64StringFromImgLink(imageSrc, imgType) {
var imageAsCanvas;
/*
* Creates a new image object from the src
* Uses the deferred pattern
*/
var createImage = function () {
var deferred = $.Deferred();
var img = new Image();
img.onload = function() {
deferred.resolve(img);
};
img.src = imageSrc;
return deferred.promise();
};
/*
* Create an Image, when loaded and start to resize
*/
$.when(createImage()).then(function (image) {
imageAsCanvas = document.createElement("canvas");
imageAsCanvas.width = image.width;
imageAsCanvas.height = image.height;
var ctx = imageAsCanvas.getContext("2d");
ctx.drawImage(image, 0, 0, imageAsCanvas.width, imageAsCanvas.height);
$scope.$apply(function($scope){
$scope.imageAsBase64String = imageAsCanvas.toDataURL(imgType);
oss.put("test.jpg", $scope.imageAsBase64String); //<-- here will be the data string i hope it works
});
}, function () {console.log('error creating an image')});
}
//How to call example
getBase64StringFromImgLink('images/george-avatar.jpg', 'image/jpeg');
<!--HTML -->
<img data-ng-src="{{imageAsBase64String}}" >

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Uploading blob file to Amazon s3

I am using ngCropImage to crop an image and want to upload it following this link:
NgCropImage directive is returning me dataURI of the image and I am converting it to a blob (after converting it I get a blob object: which has size and type), Converted DataURI to blob using following code:
/*html*/
<img-crop image="myImage" result-image="myCroppedImage" result-image-size="250"></img-crop>
$scope.myImage='';
$scope.myCroppedImage = {image: ''}
var blob;
//called when user crops
var handleFileSelect=function(evt) {
var file=evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function($scope){
$scope.myImage=evt.target.result;
});
};
console.log($scope.myCroppedImage)
reader.readAsDataURL(file);
var link = document.createElement('link');
blob = dataURItoBlob($scope.myCroppedImage)
console.log(blob)
};
angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: mimeString});
}
$scope.upload = function(file) {
//var file = new File(file, "filename");
// Configure The S3 Object
console.log($scope.creds)
AWS.config.update({ accessKeyId: $.trim($scope.creds.access_key), secretAccessKey: $.trim($scope.creds.secret_key) });
AWS.config.region = 'us-east-1';
var bucket = new AWS.S3({ params: { Bucket: $.trim($scope.creds.bucket) } });
if(file) {
//file.name = 'abc';
var uniqueFileName = $scope.uniqueString() + '-' + file.name;
var params = { Key: file.name , ContentType: file.type, Body: file, ServerSideEncryption: 'AES256' };
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert(err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
else {
// No File Selected
alert('No File Selected');
}
}
$scope.uniqueString = function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 8; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
//for uploading
$scope.handleSave = function(){
$scope.upload(blob);
}
Now, I want to upload this blob on S3 using this, but I am not able to figure out how to upload this blob file to s3 (as I am not getting 'name' in the blob file)
Any help would be really appreciated. Thanks
You can always create file from blob. You can pass file name also.
var file = new File([blob], "filename");
This same file object you can use to upload on s3.
Change your handleSave method to following. File name will be abc.png for now
//for uploading
$scope.handleSave = function(){
blob = dataURItoBlob($scope.myCroppedImage)
$scope.upload(new File([blob], "abc.png"));
}
It is not advisable that you do to put the key
secretAccessKey: $.trim($scope.creds.secret_key)
on the client side ... That is not done !, anyone can manipulate your bucket at will.

Resources