我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上载吗?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
如果可能,我需要填写数据部分吗?这是正确的方式吗?我只将文件POST到服务器端。
我一直在搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。
2019年更新:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
视图.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">
在js中
<script>
var formData = new FormData();
formData.append('file', $('#formFile')[0].files[0]);
$.ajax({
type: "POST",
url: '/GetData/UploadImage',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data);
$('#myImg').attr('src', data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
</script>
在控制器中
public ActionResult UploadImage(HttpPostedFileBase file)
{
string filePath = "";
if (file != null)
{
string path = "/uploads/Temp/";
if (!Directory.Exists(Server.MapPath("~" + path)))
{
Directory.CreateDirectory(Server.MapPath("~" + path));
}
filePath = FileUpload.SaveUploadedFile(file, path);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
使用纯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</小>
您可以使用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;
});
});