/    Sign up×
Community /Pin to ProfileBookmark

Is it possible to sent a file through ajax?

Hello.

I’m creating an Eshop website and I want the user to upload and crop an image. The problem is that I want to upload the image using ajax and not by submitting a form but getting the local url of the image is forbidden by the browsers (returns fakepath).

So is there a way to send a file though ajax or am i stuck with a form submission?

The reason I want to do that is so the user can see the image immediately after pressing the open button, so he can crop it.

The only solution I figured out until now is this:

user_presses_submit_btn -> image_goes_to_the_server -> server_sends_the_image_back_to_the_user -> user_crops_the_image -> croped_image_sented_and_posted_on_the_server

to post a comment
JavaScript

7 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 23.2019 — So is there a way to send a file though ajax or am i stuck with a form submission?[/quote]Yes, it is possible to upload a file via Ajax. After cropping the image it can be converted to a BLOB and then uploaded via Ajax. I created a demo for such procedure some time ago. I will look it up during the course of the day.

There are several cropping scripts. This one seems to be fine:

https://fengyuanchen.github.io/cropperjs/
Copy linkTweet thisAlerts:
@babaliarisauthorMay 24.2019 — I use cropperjs. The problem is that I don't know how to get the image from the user and display it in html. I searched the web and I found that you can't do that for security reasons. For example when I try to get the the image path from the user in order to display it and let him crop it, I get a fake path instead. (I'm using the file input.)

Google says you can't do that for security reasons, just select the file with the input file tag, submit the form and the browser will take care the upload of the file.

So in order to solve this, I thought a cumbersome solution to first submit the form and send it to the server, then the server redirects the user by sending him also that image in order to crop it and then send it back again cropped.

Is there a better way for achieving this?
Copy linkTweet thisAlerts:
@SempervivumMay 24.2019 — The problem is that I don't know how to get the image from the user and display it in html. I searched the web and I found that you can't do that for security reasons.[/quote]On one hand this is true: It's not possible to specify a complete path and let JS load the image from disk automatically. On the other hand it's possible to load a file when the user interacts. selects the file and thus confirms reading it. This can be done by the file input element- you know about this.

However it's not necessary to submit the form and upload the file immediately without modfiying it. You can catch the onchange event of the file input, and process the image.

The docu of cropperjs says:
new Cropper(element[, options])

were element is of type: HTMLImageElement or HTMLCanvasElement
[/quote]

The only thing that needs to be done is converting the file object to a data URL and paint it on a canvas. Then you can hand the canvas over to cropperjs.

The process of converting is described here including an example:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

Instead of setting the src of an img element you can use the dataURL to paint the image on a canvas and hand it over to cropperjs.
Copy linkTweet thisAlerts:
@SempervivumMay 24.2019 — [[2],[2,4]]
Copy linkTweet thisAlerts:
@VITSUSAMay 27.2019 — @babaliaris#1604001 Yes, it is possible to send a file through Ajax.
Copy linkTweet thisAlerts:
@4squarelogicMay 27.2019 — All files will be uploaded via AJAX or can be added within a form, and files can be renamed before uploading. Our AJAX upload will work as long as FormData is available; otherwise, the user will get a normal upload. There are three main components to our project. The multiple attributes on the file input element.
Copy linkTweet thisAlerts:
@siddhi_patelMay 28.2019 — <html>

<head>

<title>JavaScript file upload</title>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<script type="text/javascript">

var upload = function() {

var photo = document.getElementById("photo");

var file = photo.files[0];

console.log("File name: " + file.fileName);
console.log("File size: " + file.fileSize);
console.log("Binary content: " + file.getAsBinary());
console.log("Text content: " + file.getAsText(""));

var preview = document.getElementById("preview");
preview.src = file.getAsDataURL();

return false;

};

</script>

</head>

<body>

<form action="/" method="post" onsubmit="return upload();">

<fieldset>

<legend>Upload photo</legend>

<input type="file" name="photo" id="photo">

<input type="submit" value="Upload">

<hr>

<img src="" alt="Image preview" id="preview">

</fieldset>

</form>

</body>

</html>

The fileName property gives us the name of the picked up file, but not the absolute path on the filesystem, just the basename. Modify the above source code above so that the JavaScript part now becomes:

var upload = function() {

var photo = document.getElementById("photo");

// the file is the first element in the files property

var file = photo.files[0];

console.log("File name: " + file.fileName);
console.log("File size: " + file.fileSize);
console.log("Binary content: " + file.getAsBinary());
console.log("Text content: " + file.getAsText(""));
// or
// console.log("Text content: " + file.getAsText("utf8"));

return false;

};
×

Success!

Help @babaliaris spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.23,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...