Last active
March 7, 2024 05:03
-
-
Save apeckham/8da17572325f77b8cdb7 to your computer and use it in GitHub Desktop.
upload fabric canvas to s3 as png from browser
This file contains 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
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>jQuery File Upload Example</title> | |
</head> | |
<body> | |
<canvas id="c" style="border:1px solid black;"></canvas> | |
<div id="status"></div> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script> | |
<script src="//cdn.jsdelivr.net/jquery/1.9.1/jquery-1.9.1.js"></script> | |
<script> | |
$(function () { | |
var canvas = new fabric.Canvas('c'); | |
var hi = new fabric.Text('hello world', { | |
left: canvas.getWidth() / 2, | |
top: canvas.getHeight() / 2 | |
}); | |
canvas.add(hi); | |
function dataURItoBlob(dataURI) { | |
var byteString = atob(dataURI.split(',')[1]); | |
var ab = new ArrayBuffer(byteString.length); | |
var ia = new Uint8Array(ab); | |
for (var i = 0; i < byteString.length; i++) { | |
ia[i] = byteString.charCodeAt(i); | |
} | |
return new Blob([ab], {type: 'image/png'}); | |
} | |
$.get('http://localhost/fetch-keys.json', function (keys) { | |
$.ajax({ | |
url: keys.url, | |
type: 'PUT', | |
contentType: 'image/png', | |
processData: false, | |
data: dataURItoBlob(canvas.toDataURL()) | |
}).success(function () { | |
$('#status').html('success!'); | |
}).error(function () { | |
$('#status').html('error: ' + arguments.toString()); | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains 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 MyController < ApplicationController | |
BUCKET = 'my-bucket' | |
def fetch_keys | |
headers['Access-Control-Allow-Origin'] = '*' | |
headers['Access-Control-Allow-Methods'] = 'GET' | |
headers['Content-Type'] = 'application/json' | |
hex = SecureRandom.hex | |
presigner = Aws::S3::Presigner.new | |
render json: {url: presigner.presigned_url(:put_object, bucket: BUCKET, key: "#{hex}/png")} | |
end | |
end |
This file contains 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
gem 'aws-sdk', '2.0.28' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment