是否可以将文件从JavaScript传递给PHP? (最好使用ajax)。如果我们有以下代码:
<!DOCTYPE html>
<html>
<body>
<input type='file' id='upld' onChange=' f=this.files[0] '>
<input type='button' onClick='ajax_pass()'>
<script>
function ajax_pass()
{
console.log(f);
//Send 'f' using ajax to php imaginary file...
}
</script>
</body>
</html>
我是JS编程的新手,无法想象POST或GET如何包含整个图像。你可以向我澄清一下吗?
答案 0 :(得分:3)
HTML代码
<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />
Jquery代码
$(document).on("click", "#upload", function() {
var file_data = $("#myfile").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_file.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
});
});
Php代码
print_r($_FILES);
print_r($_POST);