当前位置:网站首页>Specific operations for uploading pictures in PHP
Specific operations for uploading pictures in PHP
2022-06-25 04:52:00 【Kiway.】
PHP+AJAX Upload the picture and see the preview effect , Xiaobian sees that many of them are form Form upload , It's hard to meet demand , adopt ajax Many online uploads are done directly , I didn't see any effect .
- First step
Get a button and preview area at the front of the following code , adopt js Trigger upload to server .
<div class="form-group">
<label class="col-sm-2 control-label"> picture </label>
<div class="col-md-10">
<!-- Select Picture -->
<label class="btn btn-default" for="uploadImg">
<!--lable Frame input It's for style ,for="uploadImg" Yes allow clicking lable Trigger to select Picture -->
<input type="file" multiple accept="image/*" class="sr-only" name="img" id="uploadImg" value="">
<!-- multiple Used to select multiple pictures , Only one picture can be selected if it is removed -->
<span class="docs-tooltip" data-toggle="tooltip" data-animation="false" title=""> Select Picture </span>
</label>
</div>
<div class="col-md-9 col-md-offset-2">
<div class="input-group multi-img-details" id="previewImg">
<!-- Preview picture The effect of the database can be written in a loop here -->
</div>
</div>
<script> // Select Picture trigger $("#uploadImg").on("change", function () {
// Judge image format var imgFiles = $(this)[0].files for (i = 0; i < imgFiles.length; i++) {
filePath = imgFiles[i].name fileFormat = filePath.split('.')[1].toLowerCase() src = window.URL.createObjectURL(imgFiles[i]) if (!fileFormat.match(/png|jpg|jpeg/)) {
alert(' Upload error , The file format must be :png/jpg/jpeg') return } } // Get picture information var formData = new FormData(); // Put multiple pictures into an array for (var i = 0; i < this.files.length; i++) {
formData.append('img' + i, this.files[i]) } // To upload pictures $.ajax({
// The interface to the server url: './index.php?c=upload_img', data: formData, contentType: false, processData: false, type: 'post', dataType: 'json', success: function (res) {
var preview = document.getElementById("previewImg") var len = res.filename.length; // Cyclic output for (var i = 0; i < len; i++) {
// The selected picture is placed in the preview area var div = document.createElement('div') div.className = "multi-item"; var str = ''; str += '<img class="img-responsive img-thumbnail" src="{$ip}/' + res.filename[i] + '\ " οnerrοr="this.src=\'./resource/images/nopic.jpg\'; this.title=\' Picture not found .\'">\ <input name="thumbs[]" hidden="" value="'+ res.filename[i] + '">\ <em class="close" title=" Delete this picture " οnclick="deleteMultiImage(this)">×</em>'; div.innerHTML = str; preview.appendChild(div) } } }) // After uploading, the input[file] Of value Empty , Prevent the same picture from being uploaded for the second time $("#uploadImg").attr('type','text'); $("#uploadImg").find('input').val(''); $("#uploadImg").attr('type','file'); }) // Delete the picture in the preview area function deleteMultiImage(elm) {
$(elm).parent().remove(); // After deleting the picture in the preview area input[file] Of value Empty , Prevent the same picture from being uploaded for the second time $("#uploadImg").attr('type','text'); $("#uploadImg").find('input').val(''); $("#uploadImg").attr('type','file'); } </script>
</div>
- The second step
The interface code of the server receives ajax Incoming picture file , Process the information of the picture .
// To upload pictures
public function doWebupload_img(){
// Get file information
$file = $_FILES;
// Set some variables for address linking
$year = date("Y");
$month = date("m");
// Set the storage address
$uploaddir= "images/2/" . $year . "/" . $month. "/";
// Create when folder does not exist
$dir = ATTACHMENT_ROOT . "images/2/" . $year . "/" . $month;
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
// Define an array
$filename = array();
for($i = 0;$i<count($file);$i++){
// Split the picture name
$imgname=explode(".",$_FILES['img'.$i]['name']);// Array $imgname=array('picture','jpg')
// Set a new file name
$imgname[0]=date('YmdHis') . rand(100, 999);
// The file name after uploading
$name=implode(".",$imgname);//$name=123.jpg
// The name and address of the uploaded file
$uploadfile=$uploaddir.$name;
// Upload
move_uploaded_file($_FILES['img'.$i]['tmp_name'],ATTACHMENT_ROOT.$uploadfile);
// Take the file name and address of the picture
array_push($filename,$uploadfile);
}
// return JSON data
echo json_encode(array('file'=>$file,'filename'=>$filename));
exit;
}
- design sketch


The project done by the company originally had a built-in option to upload pictures , But there are steps , Upload pictures first , Then you can select a picture from the uploaded pictures . But this situation will be complicated , And if this project is used by multiple users , Everyone is a shared folder , Each other can see the pictures uploaded by others . So I spent two days uploading and previewing , I hope I can help those in need .
边栏推荐
- Kotlin compose perfect todo project surface rendering background and shadow
- Qdebug June 2022
- 基于SSH实现的学生成绩管理系统
- How PHP gets the user's City
- Kotlin compose listens to the soft keyboard and clicks enter to submit the event
- Calculate student grade (virtual function and polymorphism)
- Le chemin de l'apprentissage immutable - - Adieu à la copie traditionnelle
- 大话云原生数据库中的存算分离
- 2.0SpingMVC使用RESTful
- In Net 6 using dotnet format formatting code
猜你喜欢

buuctf(re)

js的arguments

「 每日一练,快乐水题 」1108. IP 地址无效化

Introduction to the hardest core PWN in the whole network_ Graphic analysis

OLAP analysis engine kylin4.0

Vscade setting clang format

JS' sort() function

我的IC之旅——资深芯片设计验证工程师成长——“胡”说IC工程师完美进阶

Virtual honeypot Honeyd installation and deployment

小白一键重装官网下载使用方法
随机推荐
dotnet-exec 0.4.0 released
《牛客刷verilog》Part I Verilog快速入门
Introduction to the hardest core PWN in the whole network_ Graphic analysis
win11蓝牙无法连接怎么办?win11蓝牙无法连接的解决方法
Separation of storage and computing in Dahua cloud native database
Why does the SQL statement hit the index faster than it does not?
jsz中的join()
Sleep more, you can lose weight. According to the latest research from the University of Chicago, sleeping more than 1 hour a day is equivalent to eating less than one fried chicken leg
OpenSea PHP开发包
「 每日一练,快乐水题 」1108. IP 地址无效化
Chapter IX app project test (2) test tools
XML (VIII)
Use text analysis to identify the main gender in a text
ASEMI三相整流桥的工作原理
JS arguments
How do the defi protocols perform under this round of stress test?
parallel recovery slave next change & parallel recovery push change
执行SQL响应比较慢,你有哪些排查思路?
ORA-00800: soft external error
Opensea PHP development kit