Last active
December 17, 2015 06:19
-
-
Save delba/5564979 to your computer and use it in GitHub Desktop.
File uploading with ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| reader = new FileReader | |
| reader.onload = (e) -> | |
| @file.data = @result | |
| $('#file_field').on 'change', (e) -> | |
| reader.file = e.target.files[0] | |
| reader.readFileAsDataURL reader.file | |
| ### | |
| FileReader::oldReadAsDataURL = FileReader::readAsDataURL | |
| FileReader::readAsDataURL = (@file) -> @oldReadAsDataURL file | |
| reader = new FileReader | |
| reader.onload = (e) -> @file.data = @result | |
| $('#file_field').on 'change', (e) -> | |
| reader.readFileAsDataURL e.target.files[0] | |
| #### | |
| $('#form').on 'submit', (e) -> | |
| e.preventDefault() | |
| $.ajax | |
| url: "/upload" | |
| type: 'POST' | |
| data: { filename: reader.file.filename, data: reader.file.data } | |
| success: (data, status, xhr) -> | |
| # ... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FilesController < ApplicationController | |
| def create | |
| File.open upload_path, 'wb' do |f| | |
| f.write decoded_file | |
| end | |
| end | |
| private | |
| def decoded_file | |
| data = params[:data].gsub(/\A.+,/, '') | |
| Base64.decode64(data) | |
| end | |
| def upload_path | |
| Rails.public_path.join 'uploads', params[:filename] | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $ -> | |
| files = [] | |
| $('#file_field').on 'change', (e) -> | |
| for file in e.target.files | |
| reader = new FileReader | |
| reader.onload = (e) -> | |
| object = | |
| filename: file.name | |
| data: e.target.result | |
| files.push object | |
| reader.readAsDataURL(file) | |
| $('#form').on 'submit', (e) -> | |
| e.preventDefault() | |
| for file in files | |
| $.ajax | |
| url: "/upload" | |
| type: 'POST' | |
| data: { filename: file.filename, data: file.data } | |
| success: (data, status, xhr) -> | |
| # ... | |
| files = [] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment