[英]How to use JSON Stringify to send form-data instead of application/json with JSON .stringify()?
[英]How to send form-data as a JSON Object..?
我的服務器端有一些文本輸入和圖像。 我需要將此數據作為 JSON object 發送。 但由於 FormData,我無法發送這樣的圖像。所以我需要將我的表單數據轉換為一個 JSON object。 請幫助我...謝謝...!
HTML 部分 -
<form>
<div class="form-group">
<label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage">
</div>
</form>
Ajax 零件 -
$('#btnCreateNewAccount').click(function () {
var fileObject = $("#txtcustomerImage")[0].files[0];//access file object from input field
var fileName = $("#txtcustomerImage")[0].files[0].name; //get file name
var form = new FormData(); //setup form data object to send file data
form.append("custImage", fileObject, fileName); //append data
console.log('clicked..');
let customerNIC = $('txtcustomerNIC').val();
let customerName = $('txtcustomerName').val();
let customerAddress = $('txtcustomerAddress').val();
console.log(form)
$.ajax({
method: "post",
url: "http://localhost:8080/Sprinf_Final-Back-end/customer",
contentType: "application/json",
data: JSON.stringify({
customerNIC: customerNIC,
customerName: customerName,
customerAddress: customerAddress,
}),
success: function (res) {
if (res.massage == 'Success') {
alert('Your Account is Successfully Created!When You Log to Server Use Your User Name & Password..!');
console.log(res);
} else {
console.log('error');
}
}
});
});
如果您想將數據作為 JSON 發送,那么創建FormData
object 是沒有意義的。 您可以使用fileObject.text()
讀取文件內容並將其發送:
$('#btnCreateNewAccount').click(async function() { const fileObject = $("#txtcustomerImage")[0].files[0]; //access file object from input field const fileName = fileObject.name; //get file name const data = JSON.stringify({ fileObject: await fileObject.text(), fileName }) console.log(data); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="form-group"> <label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label> <input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage"> </div> </form> <button id="btnCreateNewAccount"> Click </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.