var file = $(‘#image’).prop(‘files’)[0]; var filename = $(‘#af_rpta_propertyland_filename’).val();
var form_data = new FormData(); form_data.append('file', file); alert(form_data); $.ajax({ type: 'POST', url: '../include/upload.php', //dataType: "json", data: { file: form_data, filename: filename }, success: function(data) { console.log(data); for (var i = 0; i < data.length; i++) { console.log("file " + i + ": " + data[i].file); } }, error: function(data) { alert('No Record Found: ' + data); } });
<input id="image" name="image" type="file" />
这就是我在PHP代码中使用Ajax上传pdf文件的方式
$file = mysql_real_escape_string($_POST['file']); $filename = mysql_real_escape_string($_POST['filename']); if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) { $tmpName = $_FILES['file']['tmp_name']; $filetype = $_FILES['file']['type']; $fp = fopen($tmpName, 'rb'); // read binary $upload[] = array('filename' => $filename,'file' => $fp); } echo json_encode($upload, JSON_UNESCAPED_UNICODE);
从我input(type file)如何将其value(the pdf file)放置到data(in ajax)以及data(ajax)如何将其传递到php文件,以便我可以检查是否$_files不为空
input(type file)
value(the pdf file)
data(in ajax)
data(ajax)
$_files
尝试json从files[0]属性创建对象,将其转换file为base64字符串
json
files[0]
file
base64
js
$("#image").on("change", function(e) { var name = $("#af_rpta_propertyland_filename").val() , file = e.target.files[0] , filename = name.length > 1 ? name + ".pdf" : file.name , filetype = file.type , filesize = file.size , data = { "filename":filename, "filetype":filetype, "filesize":filesize } , reader = new FileReader(); reader.onload = function(e) { data.file_base64 = e.target.result.split(/,/)[1]; $.post("fileupload.php", {file:data}, "json") .then(function(data) { // parse `json` string `data` var filedata = JSON.parse(data) // do stuff with `data` (`file`) object , results = $("<a />", { "href": "data:" + filedata.filetype + ";base64," + filedata.file_base64, "download": filedata.filename, "target": "_blank", "text": filedata.filename }); $("body").append("<br>download:", results[0]); }, function(jqxhr, textStatus, errorThrown) { console.log(textStatus, errorThrown) }) }; reader.readAsDataURL(file) });
的PHP
<?php if (isset($_POST["file"])) { // do php stuff // call `json_encode` on `file` object $file = json_encode($_POST["file"]); // return `file` as `json` string echo $file; };