-
Notifications
You must be signed in to change notification settings - Fork 275
Uploading through Angular
Janko Marohnić edited this page Nov 18, 2019
·
2 revisions
Using Angular 8.0 to send an image to Shrine on Rails as a formData blob.
Attach a change event to the form input file
<input type="file" (change)="sendImage($event.target.files)" />
sendImage function
sendImage(files: FileList){
this.image = files.item(0);
// upload configuration
var directUrl = "/upload"; // Shrine's upload endpoint URL
// Create a formData object
const formData: FormData = new FormData();
formData.append('file', files.item(0), this.image.name);
// Direct Upload
this.http.post(directUrl, formData).subscribe(event => {
console.log("Successfully uploaded: " + event);
this.asset.image = JSON.stringify(event);
});
}
Breakdown of the sendImage function
Convert the file (blob) to a virtual form element Ref: https://developer.mozilla.org/en-US/docs/Web/API/FormData
const formData: FormData = new FormData();
formData.append('file', files.item(0), this.image.name);
Post the picture in the background separately to the rest of your form data
this.http.post(directUrl, formData).subscribe(event => {
// Successful
});
Once we have successfully posted we get a Hash back from Shrine through Rails and it looks like this;
{"id":"4f20dae9a6af2f2857f6d1df0880dc0f.jpg","storage":"cache","metadata":{"filename":"car.jpg","size":701000,"mime_type":"image/jpeg"}}
We need to stringify this response and attach it to the object which we will be sending back to the server
this.mymodel.image = JSON.stringify(event);