如何将包含图片的FormData转换为单个JSON对象进行发送?
解决方案
你可以根据后端接口的支持情况,选择以下两种方案实现文本+图片的同步提交:
方案1:将图片转Base64封装为单JSON提交(适合接口要求必须传JSON的场景)
该方案需要将图片转为Base64字符串后放入JSON结构,仅推荐用于小体积图片,Base64编码会使图片体积增大33%左右
修改后的JS代码如下:
$('#btnCreateNewAccount').click(function () { // 先读取图片文件转为Base64 var fileObject = $("#txtcustomerImage")[0].files[0]; var reader = new FileReader(); reader.readAsDataURL(fileObject); reader.onload = function () { // 读取完成后构造JSON数据 let customerNIC = $('#txtcustomerNIC').val(); let customerName = $('#txtcustomerName').val(); let customerAddress = $('#txtcustomerAddress').val(); $.ajax({ method: "post", url: "http://localhost:8080/Sprinf_Final-Back-end/customer", contentType: "application/json", data: JSON.stringify({ customerNIC: customerNIC, customerName: customerName, customerAddress: customerAddress, custImage: reader.result // 直接传入Base64格式的图片字符串 }), success: function (res) { // 注意:原代码里massage是拼写错误,正确为message if (res.message == 'Success') { alert('Your Account is Successfully Created!When You Log to Server Use Your User Name & Password..!'); console.log(res); } else { console.log('error'); } } }); } });
后端需要对应将Base64字符串解析为图片文件存储即可
方案2:用FormData携带所有字段(更推荐,性能更高)
如果后端支持接收multipart/form-data类型的请求,直接把所有文本字段和图片都放入FormData中提交即可,不需要转JSON,性能更高也更适合大图片:
修改后的JS代码如下:
$('#btnCreateNewAccount').click(function () { var fileObject = $("#txtcustomerImage")[0].files[0]; var fileName = fileObject.name; var form = new FormData(); // 追加图片字段 form.append("custImage", fileObject, fileName); // 追加所有文本字段 form.append("customerNIC", $('#txtcustomerNIC').val()); form.append("customerName", $('#txtcustomerName').val()); form.append("customerAddress", $('#txtcustomerAddress').val()); $.ajax({ method: "post", url: "http://localhost:8080/Sprinf_Final-Back-end/customer", // 这两个配置是jQuery发送FormData必须的,不能漏 contentType: false, processData: false, data: form, success: function (res) { if (res.message == 'Success') { alert('Your Account is Successfully Created!When You Log to Server Use Your User Name & Password..!'); console.log(res); } else { console.log('error'); } } }); });
后端可以直接从form-data结构中分别获取文本字段和图片文件,不需要额外解析Base64
原有代码的错误修正
- 文本字段的jQuery选择器缺失
#号,例如$('txtcustomerNIC')需改为$('#txtcustomerNIC'),否则无法正常获取输入值 - 成功回调中的
res.massage为拼写错误,正确应为res.message
内容的提问来源于stack exchange,提问作者Gathsara
相关产品推荐
相关产品推荐

