AngularJs File Upload without FormData - javascript

I've made a simple drag and drop directive for file uploading, but my main concern is that i need to have IE8/9 support, so taking in account that FormData is not supported, how can i do a multiple file upload without using the FormData object?
Thanks in advance.
EDIT:
What i'm trying do do is this:
$scope.uploadFile = function () {
var upload = $http.post('awesomeFileThatWantsMultipleFilesUploaded.php',
angular.element(document.getElementsByClassName('droppable')).scope().files,
{withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity})
.success(function (response) {
});
return upload;
}
But the problem is that when the browser doesn't have support for FormData, i initialize the files variable as array, and then i push each file to the variable. If the file is FormData, this works.

Don't make this by hand. Is rather messy and you will always have problems. You can use a polyfill for formdata, like moxie, for angular I use angular-file-upload there is even a way to upload to S3 from the browser (here)
If you want to do it by hand, check the code in those repositories and find some ideas

Related

How to upload file in NodeJs to PocketBase

I'm working on a project where I need to upload many PDF files to a PocketBase collection.
I have all the files on my computer and I'd like to upload them using nodejs and the PocketBase JavaScript SDK. PocketBase expects me to send the file as a [file object], which is not possible in nodejs.
Ideally the code would look something like that:
const fileObject = loadFile(pathToFile);
const entry = {
nameField: "some-field",
fileField: fileObject
}
await pb.collection("my-collection").create(entry)
I didn't find any bits of code that could help creating a loadFile function.
You are supposed to send your form as multipart/form-data when uploading files to pocketbase.
Try:
const res = fetch(
"http://127.0.0.1:8090/api/collections/my-collection/records",
{
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: myFormWhichHasFiles,
}
)
Also, make sure you don't use JSON.stringify on your form when using multipart/form data.
Pro tip: if you leave out 'Content-type', it should default to multipart/form-data.

Upload local file with fetch / content-type: octet-stream

I am currently developing a Sketch Plugin, where an image gets sent to the Microsoft Custom Vision API for object detection.
The Sketch Plugin itself is written in Javascript, a fs polyfill and a fetch polyfill is available. An API call with an image url works perfectly fine. However, I have trouble sending a local file from my computer as I am not 100% how I can access it.
var templateUrl = require('../assets/test.png').replace('file://', '');
var file = fs.readFileSync(templateUrl);
var request = postData('https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/XXXXXXX/image');
request.then(data => data.json()).then(data => myFunction(data));
// post request with file
function postData(url, data) {
return fetch(url, {
method: 'POST',
headers: {
'Prediction-Key': 'XXXXXXXXXX',
'Content-Type': 'application/octet-stream',
},
body: file,
})
}
Does anyone have experience with sending local files to the image recognition API? Any help would be very much appreciated!
Thanks in advance!
Best, C

How to send file details to back end using angularjs?

Hi I am developing web application in angularjs. I am developing file upload module. I have below array with file details.
//below code to get array of files
$scope.showPicker=function()
{
var client = filestack.init('AGeDIRvVZTRWgtmFbfGuZz');
client.pick({
}).then(function (result) {
arrMakes.push(result.filesUploaded);
});
}
In the above image i shown my array. I have three files.
Below is my angular code to send details to api.
var files = new FormData();
angular.forEach(arrMakes, function (value, index) {
console.log(value,index);
files.append(index, value);
files.append('data', angular.toJson(index).replace(/['"]+/g, ''));
});
return $http.post(this.uploadUrl, files, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
}
})
The problem is i am not receiving file in server side. Below line gives me 0 files in server.
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
May i know am i sending correct data to server? Can someone help me to fix this? Any help would be greatly appreciated. Thank you.
You are not uploading any files to the server, only strings.
You can't append objects to a FormData. appart from Blob & File objects See what will happen:
fd = new FormData
fd.append(2, {foo: 'bar'})
fd.append('data', 5)
new Response(fd).text().then(console.log)
// you get [object Object]
Why do you stringify the index in "data"? It will be casted to string automatically. And what is there that you have to replace?
If i where you i would just simple send the hole arrMakes to the server and download all the files from the url on the backend, otherwise the client has to download and then upload them to the server and wasting bandwidth and time.
beside, you don't need angulars forEach loop, arrays has that method built in
arrMakes.forEach(function (value, index) {
...
})
You won't even have to use any loop if you just pass the arrMarks to the server

Upload files with Angular for PHP

I'm trying to upload a file using Angular (currently Angular 4).
But I'm unable to send it correctly. The best I can do is sending the file as a raw content (available in $_POST as some binary mess like this: )
ëPNG\r\n
\x1A\n
\x00\x00\x00\rIHDR\x00\x00\x00©\x00\x00\x008\x08\x06\x00\x00\x00Nâ2\x1F\x00\x00\n
óiCCPICC
What I want is the file to be uploaded and available in $_FILES variable in PHP.
Currently, I'm using this code in Angular
let picture = event.target.files[0];
let content = new FormData();
content.append('picture', picture, picture.name);
let headers = new Headers({'Accept': 'application/json',
'X-AUTH-TOKEN': this.user.token,
'Content-Type': picture.type});
let options = new RequestOptions({headers: headers});
this.http.post(Config.API_URL + `/user/profile/update/`, value, options).subscribe(response => {
console.log(response);
});
Currently, PHP code is just a var_dump($_FILES);
I think my problem may be related to the way Angular transforms the request.
I know there war a transformRequest option in AngularJS but I can't find how it works with Angular 4.
Do you have any suggestion on how I can make this work?
Thanks.

How do you handle download link that requires Authorization token using Angular?

I have a REST API that I'm using alongside Angular. Currently I have post objects that have file attachments. To download each file attachment, a call must be made to /get/file/{id}, but an authorization token is required each time to convey the user is logged in and has proper rights.
After much searching, I ended up with the following setup using Angular-File-Saver (which uses FileSaver.js and Blob.js):
feed.html
<p class="post-attachments text-right" ng-repeat="file in post.files">
<button type="button" class="btn-link" ng-click="feed.getFile(file)">{{file.name}}</button>
</p>
feed.controller.js
function getFile(file) {
var file_id = file.id;
PostService.GetFile(file_id).then(function(response) {
var file_type = response.headers('Content-Type');
var data = new Blob([response.data], {type: file_type});
FileSaver.saveAs(data, file.name);
}, function error(response) {
console.log(response);
});
}
While this sort-of works, there's a few big problems. Because this is different from just using an anchor link like <a href="link.com/assets/stockphoto.jpeg" download></a>, it's really a hack on downloading a file and results in poor browser support. Safari and mobile iOS don't currently work with this solution (Safari opens the file in a new window using blob:http://siteaddress.com and mobile Safari doesn't even load the file).
Additionally, there's no browser support for a progress indication. This means clicking the download doesn't actually do anything until the API returns the entire download, where the file is then shown in the browser downloads section. This results in wait times without any indication of what's happening.
What I'm wondering is this--is there a better way to handle this problem besides not requiring an authorization token each time the /get/file/{id} endpoint is called? I'm bashing my head against the wall here since this seems like a common issue but has been difficult to find answers on.
You can use angular's $http to make your request:
makeRequest = function(req){
$http(req)
.success(function(data, status){
console.log(data)
})
.error(function(data, status){
console.log(data)
})
}
// Use it
makeRequest({
method: 'POST',
url: ('/get/file/' + id),
headers: { authorization: token }
})

Categories

Resources