php - Upload images from 2 different input=file on one submit using AJAX
问题描述
I have the following code which uploads single image from input <input type="file>.
I would like to amend this so that I can add another input option (see line 7). So it would upload 2 images from 2 separate elements, on single button submit.
I would also like to submit other input from text boxes.
How could I achieve this?
Many Thanks
<div class="container">
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'>
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="file2" id="file2" name="file2" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
PHP Code:
if(isset($_FILES['file']['name'])){
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = $location;
}
}
echo $response;
exit;
}
echo 0;
解决方案
推荐阅读
- python - 为什么 fiona 在导入 geopandas 时会出错?
- java - 循环链表链接后到前,没有前参考
- html - CSS Anchor 标签不会继承显示
- java - 从片段添加到 recyclerview 并从 recyclerview 内部从 recyclerview 删除
- python-3.x - pip 没有在下载中获得分叉回购
- django - django UpdateView如何找到html表单?(命名约定)
- c++ - 为什么 std::add_lvalue_reference 的行为不符合预期?
- python - 在字符串中搜索单词的非暴力建议解决方案
- netsuite - 带有字母和数字 ID 的 NetSuite 文件类型列表
- java - Processing: How can i make a function wait before running the next line?