我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上载吗?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
如果可能,我需要填写数据部分吗?这是正确的方式吗?我只将文件POST到服务器端。
我一直在搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
您可以使用ajaxSubmit方法,如下所示:)当您选择需要上传到服务器的文件时,表单将提交到服务器:)
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
timeout: 30000,
error: function (jqXHR, textStatus) {
$('#output').html('have any error');
return false;
}
},
success: afterSuccess, // post-submit callback
resetForm: true
// reset the form after successful submit
};
$('#idOfInputFile').on('change', function () {
$('#idOfForm').ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
使用纯js更容易
异步函数saveFile(inp){let formData=新formData();formData.append(“file”,inp.files[0]);wait-fetch('/upload/somedata',{method:“POST”,body:formData});警报(“成功”);}<input-type=“file”onchange=“saveFile(this)”>
在服务器端,您可以读取请求中自动包含的原始文件名(和其他信息)。您不需要将标题“Content-Type”设置为“multipart/form-data”。浏览器将自动设置它此解决方案应适用于所有主要浏览器。
下面是更详细的代码片段,包括错误处理、超时和额外的json发送
异步函数saveFile(inp){让用户={name:'john',年龄:34};let formData=新formData();let photo=inp.files[0];formData.append(“照片”,照片);formData.append(“用户”,JSON.stringify(用户));const ctrl=新建AbortController()//超时setTimeout(()=>ctrl.art(),50000);尝试{let r=等待获取('/upload/image',{method:“POST”,body:formData,signal:ctrl.signal});console.log('HTTP响应代码:',r.status);警报(“成功”);}捕获(e){console.log('休斯顿我们有问题…:',e);}}<input-type=“file”onchange=“saveFile(this)”><br><br>在选择文件之前,打开chrome控制台>网络选项卡以查看请求详细信息。<br><br><small>因为在本例中,我们将请求发送到https://stacksnippets.net/upload/image响应代码当然是404</小>