[英]Image upload without formData
我創建了一個要上傳圖像的應用程序。 但問題是我正在發送一個永遠不等於 formData 的數據對象。 因為我根據需要修改(格式化)了數據對象以發送到服務器。
<input type="file" name="imageUrl" id="photoFile">
就像是,
var data = {
name: '',
attributes: [{}, {}]
}
為此,我想添加一個要上傳的圖像。 如果我使用表單數據,它會是這樣的。
var data = {
name: '',
attribute1: {},
attribute2: {}
}
所以,我按照要求進行了格式化,並嘗試了一整天。 卻一無所獲。
使用 Jquery 表單,您可以上傳文件並操作表單數據。 使用以下語法:
$('#form_id').ajaxForm({
beforeSerialize: function($form, options){
// do the data manipulations here and send it to options["data"]
options["data"] = processed_data;
},
dataType: 'json',
success: function(data){
//success functional logic.
}
});
有關 Jquery 表單的更多信息http://malsup.com/jquery/form/
使用 html canvas https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement轉換為 base64 並將其作為字符串發送https://developer.mozilla.org/en-US/docs/Web /API/HTMLCanvasElement/toDataURL
const getImg64 = async() => {
const convertImgToBase64URL = (url) => {
console.log(url)
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
let canvas = document.createElement('CANVAS')
const ctx = canvas.getContext('2d')
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
canvas = null;
resolve(dataURL)
}
img.src = url;
})
}
//for the demonstration purposes I used proxy server to avoid cross origin error
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg')
console.log(image)
}
getImg64()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.