post base64 编码图像到服务器使用 javascript
post base64 encode image to server using javascript
上传图片到服务器,图片来自,然后我想通过ajax将post图片上传到服务器,服务器端使用python flask框架,需要base64编码格式,问题是我如何使用 javascript 将图像转换为 base64 格式。
$('.img-upload-btn').click(function(event) {
$("#img-upload").click();
});
$('#img-upload').on('change', function(event) {
event.preventDefault();
var img = $("#img-upload")[0].files[0];
console.log(toDataUrl(img.name));
var img_data = {
"spec_id": 212,
"file": img
};
console.log(img);
$.ajax({
url: 'http://10.0.0.75:5000/api/check_specification',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
failure:function(errorMsg) {
alert(errorMsg);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-search full-width img-upload-btn">upload-img</button>
<input type="file" id="img-upload" >
像这样你可以在 base64 中获取图像。
fileChange(e) {
/* any way to get the object input */
var file = document.querySelector('input[type=file]');
let reader = new FileReader();
if(file.files[0]) {
reader.onload = () => {
imgBase64 = reader.result;
console.log(reader.result);
//your request
}
reader.readAsDataURL(file[0]);
}
}
上传图片到服务器,图片来自,然后我想通过ajax将post图片上传到服务器,服务器端使用python flask框架,需要base64编码格式,问题是我如何使用 javascript 将图像转换为 base64 格式。
$('.img-upload-btn').click(function(event) {
$("#img-upload").click();
});
$('#img-upload').on('change', function(event) {
event.preventDefault();
var img = $("#img-upload")[0].files[0];
console.log(toDataUrl(img.name));
var img_data = {
"spec_id": 212,
"file": img
};
console.log(img);
$.ajax({
url: 'http://10.0.0.75:5000/api/check_specification',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
failure:function(errorMsg) {
alert(errorMsg);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-search full-width img-upload-btn">upload-img</button>
<input type="file" id="img-upload" >
像这样你可以在 base64 中获取图像。
fileChange(e) {
/* any way to get the object input */
var file = document.querySelector('input[type=file]');
let reader = new FileReader();
if(file.files[0]) {
reader.onload = () => {
imgBase64 = reader.result;
console.log(reader.result);
//your request
}
reader.readAsDataURL(file[0]);
}
}