不使用任何形式,我可以使用jQuery使用POST方法将文件/文件从<input type="file">
发送到'upload.php'。输入标记不在任何表单标记内。它独立。所以我不想使用像'ajaxForm'或'ajaxSubmit'这样的jQuery插件。
答案 0 :(得分:79)
您可以使用 FormData 通过POST请求提交数据。这是一个简单的例子:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
只要您知道自己的请求设置(如网址,方法和参数数据),就不必使用表单发出ajax请求。
答案 1 :(得分:22)
此处的所有答案仍在使用FormData API。这就像没有表单的"multipart/form-data"
上传。您也可以使用POST
将文件作为内容直接上传到xmlHttpRequest
请求的正文中,如下所示:
var xmlHttpRequest = new XMLHttpRequest();
var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);
Content-Type
和Content-Disposition
标头用于解释我们发送的内容(mime类型和文件名)。
我也发布了类似的答案here。
答案 2 :(得分:11)
基于this tutorial,这是一个非常基本的方法:
$('your_trigger_element_selector').on('click', function(){
var data = new FormData();
data.append('input_file_name', $('your_file_input_selector').prop('files')[0]);
// append other variables to data if you want: data.append('field_name_x', field_value_x);
$.ajax({
type: 'POST',
processData: false, // important
contentType: false, // important
data: data,
url: your_ajax_path,
dataType : 'json',
// in PHP you can call and process file in the same way as if it was submitted from a form:
// $_FILES['input_file_name']
success: function(jsonData){
...
}
...
});
});
不要忘记添加正确的错误处理
答案 3 :(得分:8)
步骤1:创建HTML页面放置HTML代码。
步骤2:在HTML代码页底部(页脚)创建Javascript:并将Jquery代码放在脚本标记中。
第3步:创建PHP文件和PHP代码复制过去。在$.ajax
代码url中的Jquery代码后,在你的php文件名中应用哪一个。
<强> JS 强>
//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button
$(document).on("click", "#upload", function() {
var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar", // Upload Script
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
// Do something after Ajax completes
}
});
});
<强> HTML 强>
<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />
<强>腓强>
print_r($_FILES);
print_r($_POST);
答案 4 :(得分:2)
很抱歉那个人但是AngularJS提供了一个简单而优雅的解决方案。
以下是我使用的代码:
ngApp.controller('ngController', ['$upload',
function($upload) {
$scope.Upload = function($files, index) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
file: file,
url: '/File/Upload',
data: {
id: 1 //some data you want to send along with the file,
name: 'ABC' //some data you want to send along with the file,
},
}).progress(function(evt) {
}).success(function(data, status, headers, config) {
alert('Upload done');
}
})
.error(function(message) {
alert('Upload failed');
});
}
};
}]);
&#13;
.Hidden {
display: none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-controller="ngController">
<input type="button" value="Browse" onclick="$(this).next().click();" />
<input type="file" ng-file-select="Upload($files, 1)" class="Hidden" />
</div>
&#13;
在服务器端,我有一个带有操作的MVC控制器,它保存在Request.Files集合中找到的上传文件并返回一个JsonResult。
如果你使用AngularJS试试这个,如果你不...对不起交友: - )
答案 5 :(得分:1)
非 jquery (React) 版本:
JS:
function fileInputUpload(e){
let formData = new FormData();
formData.append(e.target.name, e.target.files[0]);
let response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
let result = await response.json();
console.log(result.message);
}
HTML/JSX:
<input type='file' name='fileInput' onChange={(e) => this.fileInput(e)} />
您可能不想使用 onChange,但您可以将上传部分附加到任何其他函数。
答案 6 :(得分:0)
试试这个puglin simpleUpload,不需要表格
HTML:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
使用Javascript:
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#enviar',
success: function(data){
alert('Envio com sucesso');
}
});