Skip to content

Instantly share code, notes, and snippets.

@johnny12150
Last active August 8, 2021 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnny12150/2c1ab2efe552fd24e541cad96ad2e161 to your computer and use it in GitHub Desktop.
Save johnny12150/2c1ab2efe552fd24e541cad96ad2e161 to your computer and use it in GitHub Desktop.
純JS - 照片上傳、下載與預覽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
width: 150px;
margin-bottom: 10px;
margin-right: 10px;
vertical-align: middle;
}
</style>
</head>
<body>
<!-- https://pjchender.blogspot.com/2019/01/js-javascript-input-file-upload-file.html -->
<input type="file" id="file-uploader" data-target="file-uploader" accept="image/png" multiple="multiple"/>
<img id='preview'>
</body>
<script>
const fileUploader = document.querySelector('#file-uploader');
fileUploader.addEventListener('change', (e) => {
console.log(e.target.files); // get list of file objects
display_img(e.target.files);
upload_img(e.target.files[0]); // pass blob
});
function display_img(curFiles) {
const curFile = curFiles[0]; // 透過 input 取得的 file object
const reader = new FileReader();
// 這會在readAS後才執行
reader.onload = function (e) {
// console.log('file:', e.target.result); // base64
document.querySelector('#preview').src = e.target.result;
};
// to data url
reader.readAsDataURL(curFile);
}
function blob2buffer(blob) {
return new Promise((resolve, reject) => {
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function (event) {
arrayBuffer = event.target.result;
resolve(arrayBuffer);
};
fileReader.readAsArrayBuffer(blob);
return arrayBuffer;
});
}
function display_arr_img(arr) {
document.querySelector('#preview').src = URL.createObjectURL(new Blob([new Uint8Array(arr)], {type: "image/png"}));
}
async function upload_img(pic) {
url = 'http://localhost:3000/upload/json/img_raw';
arrayBuffer = await blob2buffer(pic);
fetch(url, {
method: 'POST',
// flask need to set header of json
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
item_id: 1,
format: 'png',
img: Array.from(new Uint8Array(arrayBuffer)),
}),
}).then((res)=> {
return res.json()
}).then((json) => {
// 拿到js array
display_arr_img(json['img']);
})
}
</script>
</html>
import flask
import pymysql
from flask_cors import CORS
import json
app = flask.Flask(__name__)
CORS(app)
connection = pymysql.connect(host='localhost', user='root', password='password', db='db01', charset='', cursorclass=pymysql.cursors.DictCursor)
@app.route('/upload/json/img_raw', methods=['POST'])
def raw_img():
json_data = flask.request.json
# save to db
with connection.cursor() as cursor:
sql = "UPDATE table1 SET `img_raw`=%s WHERE id=%s"
try:
# img現在是list, 可以用json string/ byterarray/ base64存進資料庫
cursor.execute(sql, (json.dumps(json_data['img']), json_data['item_id']))
connection.commit()
except Exception as err:
connection.rollback()
return flask.jsonify({'err': err})
# get a picture
sql = "SELECT * FROM table1"
cursor.execute(sql)
result = cursor.fetchone()
r = result[0]['img_raw']
r = json.loads(r.decode()) # utf-8, 也可用ascii
return flask.jsonify({'img': r})
PyMySQL
Flask
flask-cors
@johnny12150
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment