form data is not appending file object - angularjs

I have a problem in appending file object with form data,after appending file object to form data,form data is empty object.Please suggest
scope.uploadDigitalSignature = function (form) {
if (scope.digitalFiles.length) {
scope.docDetails.aliasName = scope.docDetails.aliasName;
scope.docDetails.digipassword = scope.docDetails.digipassword;
scope.docDetails.certificate = scope.docDetails.certificate;
var file = scope.digitalFiles[0];
var formData = new FormData(this);
formData.append('file', file);
// FileUpload.upload(scope.digitalFiles,docId,function(success,blobData){
var config = {
headers: {
'Content-Type': 'multipart/form-data',
}
};
var blobData = {
"file" : scope.docDetails.certificate
};
AdminService.uploadDigitalSignature(function(){
toastr.success('Signature uploaded successfully');
},docId,scope.docDetails.aliasName,scope.docDetails.digipassword ,blobData,config);
//}
//);
}
};

A FormData Object is an exotic object whose contents is not directly available to JavaScript.
To retrieve the contents of a FormData object, use its .entries() method:
var contents = Array.from(formData.entries());
console.log(contents);
For more information, see MDN Web API Reference - FormData.entries()

Related

How to use foreach for ajax array in Laravel?

I have an ajax function where I post multiple files in an array. How can store these files? I tried the following code in controller but only the first file is being stored.
foreach ($request->photos as $imagefile) {
$imageName = $imagefile->getClientOriginalName();
$imagePath = public_path('folder-path/');
$imagefile->move($imagePath,$imageName);
}
also this is how my array looks like
array from ajax
as #innovin requested.
Blade File
<input name="files[]" type="file" class="form-control" accept="image/png, image/jpeg" multiple id="files">
Update
function otherUpload(){
var outputdata = [];
var fileSelect = document.getElementById('files');
var files = fileSelect.files;
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('photos[]', file, file.name);
}
$.ajax({
type: "POST",
url: 'post-url',
contentType: false,
processData: false,
dataType:'json',
data: formData,
success:function(data) {
if(data.code == 1){
console.log(data);
fetchOtherImages();
}
}
});
}
</script>```
you should loop through $request->file('photos') instead of $request->photos
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $photo)
{
$name = $photo->getClientOriginalName();
$file->move(public_path('folder-path'), $name);
// to store file in Storage folder:
//$file->storeAs('files', $name);
}
}
note that he function GetClientOriginalName() is used to retrieve the file's original name at the time of upload in laravel, and that'll only be possible if the data is sent as array and not as a string. Hence, you must add enctype="multipart/form-data" whenever you are creating a form with input fields for files or images.

How can i generate a blob url?

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

angularJS hit ASP.MVC controller to export excel

I have an MVC controller to export excel file :
public ActionResult exportExcelBankData(BankDataViewModel viewModel) {
List<BankDataViewModel> bankDatas = (List<BankDataViewModel>)Session["bankDatas"];
bankDatas = bankDatas.OrderBy(x => x.completeLoading).ToList();
using (var package = new ExcelPackage()) {
var stream = new MemoryStream();
string fileName = "bankData.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//fill rows and columns
package.SaveAs(stream);
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
and here my angularjs function to hit the controller
labAnalysisService.exportExcel = function (val, obj) {
return $http.get( val, //url to controller
{ params: obj, //parameter
headers: { 'Accept': 'application/json' }
});
}
and I'am still unable to export the excel.
any suggestion?
A File returned with ajax call will not be downloaded, you have to make following changes.
Make request of the excel download by opening a new window of browser through java script like this
window.open(
"Controller/Action?args=" + encodeURIComponent(val),
"_blank");

how to export data into CSV and PDF files using angularjs

I want to, when i click on button (separate for both CSV and PDF), it automatically download in CSV and PDF file with correct Formatting.
this CSV code i want to add PDF inside code
$scope.downloadData = function() {
var datasets = $scope.datasets.reverse();
var file_name = $scope.m_id+ '.csv';
var dataUrl = 'data:text/csv;charset=utf-8,';
var json = [];
if(datasets !== null) {
for(idx = 0; idx < datasets.length; idx++) {
var dataset = datasets[idx].data;
var time = datasets[idx].timestamp;
time = $filter('date')(time, "dd/MMMM/yyyy-hh:mm a");
dataset.time = time;
json.push(dataset);
}
var fields = Object.keys(json[0]);
var csv = json.map(
function(row) {
return fields.map(
function(fieldName) {
return '"' + (row[fieldName] || '') + '"';
}
);
}
);
csv.unshift(fields);
var csv_str = csv.join('%0A');
var downloadURL = dataUrl + csv_str;
var saveAs = function(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.target = "_blank";
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
};
saveAs(downloadURL, file_name);
} else {
$scope.err_msg = 'Failed to get data. Try reloading the page.';
}
};
I try some of script i found on internet, but it is not working, some have formatting issue and save have downloading.
In Advance Thanks.
You should use this awesome library for pdf/csv or whatever else formats.. File Saver
Here's is code example, service created using FileSaver
function download(api, file, contentType) {
var d = $q.defer();
$http({
method: 'GET',
url: api,
responseType: 'arraybuffer',
headers: {
'Content-type': contentType
}
}).success(function(response) {
var data = new Blob([response], {
type: contentType+ ';charset=utf-8'
});
FileSaver.saveAs(data, file);
d.resolve(response);
}).error(function(response) {
d.reject(response);
});
return d.promise;
}
file input is name of file, you can use same service and pass the types and file names direct from controller.
Let;s you service name is homeService
for pdf call
homeservice.download('/api/download/whaever', 'export.pdf', 'application/pdf')

Angular ng-file-upload Get Byte Array and FormData in Asp.net MVC

I am trying to use ng-file-upload to upload files using Angular. I need the byte array to store in our database (I cannot store the uploaded file on the server), but I also need the FormData as well. My problem is that I can only seem to get one or the other (either the byte array or the formdata) but not both.
Here is my Angular code:
$scope.uploadPic = function (file) {
$scope.emrDetailID = 7;
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/api/Document/UploadEMRDocument',
method: 'POST',
data: { file: file, 'emrdetail': $scope.emrDetailID}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
$scope.imageID = file.result;
});
});
};
Using the code below, I can get the byte array and store it in my database:
public async Task<IHttpActionResult> UploadDocument()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
string ClientIP = IPNetworking.GetIP4Address();
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var extension = Path.GetExtension(filename).TrimStart('.');
var buffer = await f.ReadAsByteArrayAsync();
FileImageParameterModel pm = new FileImageParameterModel();
pm.binFileImage = buffer;
//pm.CompanyID = UserInfo.intMajorID;
pm.CompanyID = 10707;
pm.dteDocumentDate = Convert.ToDateTime("4/4/2016");
pm.dteExpiration = Convert.ToDateTime("4/4/2017");
pm.vchUserIP = ClientIP;
pm.vchUploadedbyUserName = UserInfo.Username;
pm.vchFileExtension = extension;
CommonClient = new CommonWebApiClient();
CommonClient.AuthorizationToken = UserInfo.AccessToken;
int imageID = await CommonClient.InsertNewFileImage(pm);
return Json(imageID);
}
else
{
return BadRequest("Attachment failed to upload");
}
}
Using the code below I can get the FormData
var provider = new MultipartFormDataStreamProvider(workingFolder);
await Request.Content.ReadAsMultipartAsync(provider);
var emr = provider.FormData["emrdetail"];
but then I can't get the byte array as using MultipartFormDataStreamProvider wants a folder to store the file.
There's got to be a way to get both. I have been searching the internet for 2 days and all I can find are the two solutions above neither of which solves my issue.
Any assistance is greatly appreciated!
You are thinking way to complicated. Here is some of my code which I used for file upload in AngularJS with .NET
Angular:
function uploadFileToUrl(file) {
var formData = new FormData(); // Notice the FormData!!!
formData.append('uploadedFile', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: {
'Content-Type': undefined
}
}).then(resolve, reject);
function resolve(data) {
$log.debug('data : ', data);
return data;
}
function reject(e) {
$log.warn('error in uploadFileToUrl : ', e);
return $q.reject(e);
}
}
Server:
public Task HandleAsync([NotNull] UploadFilesCommand command)
{
return wrapper.InvokeOnChannel(async client =>
{
// init command
command.Output = new Dictionary<string, int>();
try
{
foreach (var file in command.Files)
{
var request = new UploadFileRequest
{
FileName = file.Name,
FileStream = file.Stream
};
UploadFileResponse response = await client.UploadFileAsync(request);
command.Output.Add(file.Name, response.Id);
}
}
finally
{
// dispose streams
foreach (var file in command.Files)
{
if (file.Stream != null)
{
file.Stream.Dispose();
}
}
}
});
}

Resources