![](/img/trans.png)
[英]jQuery or AngularJS Ajax “POST” request to server using code below however do not sending param data to server.
[英]Sending an image and JSON data to server using Ajax POST request?
我想發送用戶從他們的機器中選擇的圖像以及所有包裝在JSON對象中並發送到服務器的表單數據。 我正在使用Node作為服務器。 是否可以將圖像與其他表單元素一起放在JSON對象中並在Node中讀取?
我遇到的常見方法是使用Base64字符串方法:將圖像編碼為Base64字符串,並將其設置為您發送到服務器的JSON對象的一部分。
另一種方法似乎是在JSON中使用二進制數據,但我之前從未嘗試過這樣做,因此我沒有太多信息。
這是在Javascript中執行Base64編碼的代碼示例。 具體來看下面的方法
function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
var canvas = document.createElement("canvas");
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
有一種方法可以實現這一點:使用圖像數據。
在Javascript中,在客戶端,FileReader將允許您讀取二進制圖像數據,並將它們轉換為base64編碼的字符串。
在客戶端:
var file = $('.file-upload > input')[0].files[0];
function upload(file) {
var reader = new FileReader();
// when image data was read
reader.onload = function(event) {
// I usually remove the prefix to only keep data, but it depends on your server
var data = event.target.result.replace("data:"+ file.type +";base64,", '');
// make here your ajax call
$.ajax({
url: 'and_so_on',
json: {
data: data
}
});
// read data from file
reader.readAsDataURL(file);
}
在服務器端,您將收到base64編碼的圖像,您可以使用Buffer構造函數輕松地將其轉換為二進制文件
var buffer = new Buffer(data, 'base64');
請注意, 並非所有瀏覽器都支持 FileReader
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.