I want to upload an image use something like
<form ...>
<input type="file" id="upload"></input>
</form>
the form does not have a submit button, I make a div to replace it:
<div id="submit"></div>
I hope that when the div is clicked, the image in will be uploaded and then showed in another img without refresh.
I know I need to use ajax but I don’t know how to realize it with jQuery and Rails.
Following is my questions:
-
How to post the uploaded file to controller
I tried to use $.post, but $(“#upload”).val() only returns the file path, no content.
-
Here is my idea to achieve my goal, can it work?
(1)bind a function to $(“#submit”).click, post the file to controller
(2)the controller save the file in /public folder, render the file url
(3)define a function as callback of the $.post in which set the src of some to the url
If my idea has any problem, please tell me a right way…
Thank you!!
The best solution is to use jQuery plugin which will help you to resolve your problem.
When image is uploaded just return JSON as response with the location to your image.
Then with jQuery or pure JavaScript update “src” attribute of an image.
JSON
JS to execute on successful upload
where data is JSON returned to you from server.