ajax - 将 ajaxform 与 ajax 合并以上传图片
问题描述
我尝试在我的 nodejs 站点中创建上传照片。我使用此代码选择文件并上传图像:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
使用 loadfile 函数我选择我的图像,并使用 Uploadfile 函数我用 ajax 上传图像。如果我单独使用它,它的工作完美,并将图像上传到该位置。但是当我尝试将此代码添加到我的代码中时,它会产生很多错误。在我的代码中,我将 pug 文件中的所有表单发送到后端:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
我尝试将 ajaxform 与 ajax 合并,但是当我合并 formdata 或我发送 ajaxform 时,文件的数据是发送错误。我如何合并代码?谢谢你的帮助。
解决方案
尝试提交表单,它将使用您的图像提交表单。
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
推荐阅读
- sql - UNION ALL 未按预期执行 - Oracle SQL
- python - 在 Azure Functions 中导入 Google Cloud python 库时出错
- javascript - 当我尝试将其作为道具传递给其他组件时,获取响应返回未定义
- nosql - 是否使用 Kafka Streams 和/或 KSQL 对来自数据库的数据流进行非规范化处理
- mysql - 在 MySQL 8.0 中,我有一个数据字段类型为 GEOMETRY 的列。为什么我的查询中的值没有一致地显示?
- javascript - 单击按钮时删除交叉并转到下面的行
- android - 我在 android studio 模拟器中运行的应用程序没有加载 localhost 数据库内容
- signalr-hub - 将复杂对象从 signalR .NET Core 3.0 集线器发送到 clientIn
- sql - 我可以在子查询中使用“LIKE”吗
- reactjs - React:按属性值获取标签列表