我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上载吗?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
如果可能,我需要填写数据部分吗?这是正确的方式吗?我只将文件POST到服务器端。
我一直在搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。
以下是我如何做到这一点:
HTML
<input type="file" id="file">
<button id='process-file-button'>Process</button>
JS
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
PHP
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
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']
我想到了一个主意:
Have an iframe on page and have a referencer.
具有将输入类型文件元素移动到的表单。
Form: A processing page AND a target of the FRAME.
结果将发布到iframe,然后您只需将获取的数据发送到所需的图像标签,如下所示:
data:image/png;base64,asdfasdfasdfasdfa
并加载页面。
我相信这对我来说是有效的,取决于你是否能够做到:
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
使用纯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</小>