在上传文件和大图像时,我的表单工作得很好。对于任何太大的图像,都可以使用画布进行调整大小,然后将其附加到“数据”表单中,从而可以完美保存。但是,现在我被要求允许将视频和音频文件上传到同一文件输入中。
这种情况让我有些困惑,因为即使手机的较短视频可以达到50MB或更多,特别是在相机质量不错的情况下。我搜索了很多东西,但似乎找不到与我正在进行的提交过程已经有些兼容的东西。 我看到我可以将文件拆分为多个块,然后将其分段上传到服务器,但是另一个不幸的部分是,当我提交文件(图像,pdf,mp4,mp3)时,我还在提交其他信息,例如Description(小段)描述文件),提交文件的人的姓名等。
我当前的流程有点像这样:
人员上传文件+信息,我使用formData
和new XMLHttpRequest()
发送出去。
在服务器端,我得到名称,设置路径并获得提交的日期。图像/文件的名称更改为20200128200812_imageName.jpeg
之类的名称,这有助于我根据提交表单的时间(数据库列frmSubmitted)检索图像。
我正在尝试做的事情: 允许用户提交具有处理视频类型和音频类型的能力的表单,但仍可以处理与文件关联的信息,例如名称或描述。
恐怕如果我分批提交视频或音频文件,我也会提交其他信息,对此我可能是错的,但是我读过的所有其他帖子似乎都提到提出单独的请求可能是唯一的方法。以下代码可以正常工作,并且是我目前的设置方式,但我将其包含在上下文中。
html
<input type="text" id="name"/>
<textarea id="description" name="description" rows="5" cols="50" maxlength="2000"></textarea>
<input type="file" name="sFile" id="sFile" multiple />
<button onclick="submitFile();" class="btn" >submit</button>
JS
function submitFile(){
const files= document.querySelector('#sFile').files;
var formData = new FormData();
if (files.length > 0){
for (var i = 0; i < files.length; i++) {
var file= files[i];
if(checkFileExtension(file) && checkFileSize(file)){ //checks the file for images and the size of the image
image = resizeImage(file);
formData.append('images[]', image);
}else{
formData.append(file[], file);
}
}
}
/*
*getting values & error handling...
*/
//appending values
formData.append('desc', description);
formData.append('personName', name);
var postrequest = new XMLHttpRequest();
postrequest.open('post', 'include/fileProcessing.php', true);
postrequest.send(formData);
postrequest.onload = function(){
var data = JSON.parse(postrequest.responseText);
if(data.result == 'true' ){
alert('Form has been submitted!');
}
php
$date = date('YmdHis');
if (isset($_FILES['images'])) {
$errors = [];
$path = '../images/uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'];
$all_files = count($_FILES['images']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$original_Name = $_FILES['images']['name'][$i];
$file_name = $date .'_'.$original_Name;
$file_tmp = $_FILES['images']['tmp_name'][$i];
$file_type = $_FILES['images']['type'][$i];
$file_size = $_FILES['images']['size'][$i]/1024;
$file_ext = strtolower(end(explode('.', $_FILES['images']['name'][$i])));
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Image type not allowed: ' . $original_Name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors = 'Image size too large';
}
$file = $path . $file_name;
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) $rtVariables['picErrors'] = $errors;
}
/**check and upload files that are not images but too long to post**/
任何帮助将不胜感激。