Reputation: 2466
URL.createObjectURL(event.target.files[0] this makes me able to view the image just uploaded in the browser. Using the same hack is there a way, where I can store the file/image into a folder instead of URL?
console.debug(URL.createObjectURL(event.target.files[0]));
the above logs out, this: blob:http%3A//mysite.localhost.com/f96c26b4-9938-4f6e-941e-edbdae3454c9
I just wonder if I can replace mysite.localhost.com
with folder path. I even tried replacing URL with full path to a folder, but createObjectURL
only work on URL
. Is there any function to save file into folder?
Upvotes: 3
Views: 5934
Reputation: 137006
Per your comment
I want to save on server side..
the answer becomes "yes it's possible".
First let's explain your misconception :
The string returned by the method URL.createObjectURL()
is an URI pointing to some place in the browser's memory, where the Blob passed as first argument will be accessed as a file.
This file is not accessible otherwise than through this URI, and this URI is only available for the current session. You can't share it nor access it from an other machine, nor even from the same machine with an other browser. It will be deleted when the document who called it will be closed (in some implementations, it needs an hard-refresh).
But what you need is actually to save the Blob you passed.
This can be achieved quite easily thanks to the FormData
Object, which will allow you to send it through an XHR request.
input.onchange = function() {
var formData = new FormData();
formData.append('file', this.files[0], 'yourFileName.ext');
var xhr = new XMLHttpRequest();
xhr.onload = callback; // assuming you've got a callback function
xhr.open('POST', yourServerSideFileHandlerScript);
xhr.send(formData);
};
or with jQuery,
$(input).on('change', function() {
var formData = new FormData();
formData.append('file', this.files[0], 'yourFileName.ext');
$.ajax({
url: yourServerSideFileHandlerScript,
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: callback
});
});
You then will be able to get it server-side as any file upload.
Example server-side code (here php):
if ( isset( $_FILES["file"] ) ){
$dir = 'some/dir/';
$blob = file_get_contents($_FILES["file"]['tmp_name']);
file_put_contents($dir.$_FILES["file"]["name"], $blob);
}
Upvotes: 8