【发布时间】:2021-11-05 05:50:11
【问题描述】:
我正在尝试使用 XMLHttpRequest 上传图像,一切都在网络浏览器上完美运行,但在手机上却无法运行。 正确显示进度百分比,在 LOG 文件中没有发现错误。
直到几天前这段代码在所有设备上都能完美运行,自从托管服务提供商升级系统以来,我一直面临着许多问题。
请指教出了什么问题, 谢谢。
Javascript:
function fileSelected() {
var count = document.getElementById('attachment').files.length;
if( count > 0 ){
$("#attachment").prop('disabled', true);
$('#submitButton').hide();
$('#uploadButton').show();
}
}
function uploadFile() {
var fd = new FormData();
fd.append("attachment", document.getElementById('attachment').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php");
xhr.send(fd);
}
function uploadProgress(e) {
if (e.lengthComputable) {
var percentComplete = Math.round(e.loaded * 100 / e.total);
document.getElementById('progress').innerHTML = '<b>Attachment</b> ' + percentComplete.toString() + '% Uploaded';
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadComplete(e) {
var resp = e.target.responseText;
var respArr = resp.split('-');
if( respArr[0] == "successful" ){
$("#uploadedAttachment").val(respArr[1]);
$('#submitButton').show();
$('#uploadButton').hide();
document.getElementById("upload_file").style.display = "none";
}
}
function uploadFailed(e) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(e) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
上传.php
if (isset($_FILES['attachment'])) {
$file_tmp = $_FILES['attachment']['tmp_name'];
$file_with_ext = explode(".", $_FILES['attachment']['name']);
$file_ext = strtolower($file_with_ext[1]);
$file_name_new = md5(uniqid().mt_rand()).".".$file_ext;
move_uploaded_file( $file_tmp, "attachments/" . $file_name_new );
echo "successful-{$file_name_new}";
}
表格:
<form id="AddComplaint" name="AddComplaint" method="POST" action="" enctype="multipart/form-data" autocomplete="off">
<div class="field" id="upload_file">
<div class="ui action input">
<input type="text" placeholder="Browse_Picture">
<input type="file" name="attachment" id="attachment" onchange="fileSelected();" accept="image/*" capture="camera">
</div>
</div>
<div class="field">
<input type="hidden" id="uploadedAttachment" name="rec[uploadedAttachment]" value="" />
<div id="progress"></div>
</div>
<div class="field">
<button type="button" id="uploadButton" style="display:none;" onclick="uploadFile()"><i aria-hidden="true" class="upload icon"></i><span>UPLOAD</span></button>
<button type="submit" id="submitButton"><i aria-hidden="true" class="send icon"></i><span">SEND</span></button>
</div>
</form>
【问题讨论】:
标签: php ajax file-upload xmlhttprequest