php에서 다중 파일 업로드
여러 파일을 업로드하여 폴더에 저장하고 경로를 가져와 데이터베이스에 저장합니다.여러 파일 업로드를 수행하는 데 필요한 좋은 예가 있으면...
참고: 파일 유형은 모두 지정할 수 있습니다.
오래된 게시물인 것은 알지만 여러 파일을 업로드하려는 사용자에게 좀 더 자세한 설명이 도움이 될 수 있습니다.필요한 것은 다음과 같습니다.
- 입력 이름을 배열로 정의해야 합니다.
name="inputName[]" - 입력 요소에는 다음이 있어야 합니다.
multiple="multiple"아니면 그냥multiple - PHP 파일에서 구문을 사용합니다.
"$_FILES['inputName']['param'][index]" - 어레이에 빈 문자열이 포함되어 있을 수 있으므로 빈 파일 이름과 경로를 찾아야 합니다.사용하다
array_filter()세기 전에
아래는 (관련된 코드만 표시) 다운된 더티한 예입니다.
HTML:
<input name="upload[]" type="file" multiple="multiple" />
PHP:
//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
도움이 됐으면 좋겠네요!
여러 파일을 선택하여 업로드 할 수 있습니다.
<input type='file' name='file[]' multiple>
업로드를 실행하는 샘플 php 스크립트:
<html>
<title>Upload</title>
<?php
session_start();
$target=$_POST['directory'];
if($target[strlen($target)-1]!='/')
$target=$target.'/';
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
$temp=$target;
$tmp=$_FILES['file']['tmp_name'][$count];
$count=$count + 1;
$temp=$temp.basename($filename);
move_uploaded_file($tmp,$temp);
$temp='';
$tmp='';
}
header("location:../../views/upload.php");
?>
</html>
선택한 파일은, 다음과 같은 배열로 수신됩니다.
$_FILES['file']['name'][0]첫 번째 파일의 이름을 저장합니다.
$_FILES['file']['name'][1]두 번째 파일의 이름을 저장합니다.
기타 등등.
이 간단한 대본이 저한테는 효과가 있었어요.
<?php
foreach($_FILES as $file){
//echo $file['name'];
echo $file['tmp_name'].'</br>';
move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}
?>
HTML
와의 불화를 초래하다
id='dvFile';을 작성하다
button;onclick해당 버튼 호출 기능의add_more()
자바스크립트
function add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
PHP
if(count($_FILES["item_file"]['name'])>0)
{
//check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
{ //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path))
{
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
//Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //No file upload message
}
이 방법으로 파일/이미지를 필요한 만큼 추가하여 php 스크립트를 통해 처리할 수 있습니다.
하나의 파일을 업로드하는 것과 크게 다르지 않습니다.$_FILES는 업로드된 모든 파일을 포함하는 배열입니다.
PHP 매뉴얼에는 다음과 같은 장이 있습니다.여러 파일 업로드
사용자 측에서 여러 파일 업로드를 쉽게 선택할 수 있도록 하려면(업로드 필드를 입력하는 대신 여러 파일을 동시에 선택) SWFUpload. 그러나 일반 파일 업로드 양식과는 다르게 작동하며 플래시가 작동해야 합니다.
SWFUpload는 Flash와 함께 폐지되었습니다.이제 올바른 접근법에 대해서는 다른 새로운 답변을 확인하십시오.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$max_no_img=4; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))
{
//echo $key;
//echo "<br>";
//echo $value;
//echo "<br>";
if(!empty($value)){ // this will check if any blank field is entered
$filename =rand(1,100000).$value; // filename stores the value
$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "upload/$filename"; // upload directory path is set
//echo $_FILES['images']['type'][$key]; // uncomment this line if you want to display the file type
//echo "<br>"; // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add);
echo $add;
// upload the file to the server
chmod("$add",0777); // set permission to the file.
}
}
?>
</body>
</html>
간단히 말하자면, 먼저 파일 어레이를 세고 나서 루프 중에 간단하게 다음과 같이 할 수 있습니다.
$count = count($_FILES{'item_file']['name']);
총 파일 수를 맞췄습니다.
그 사이에 루프는 다음과 같이 합니다.
$i = 0;
while($i<$count)
{
Upload one by one like we do normally
$i++;
}
여기 내가 쓴 함수가 좀 더 이해하기 쉽게 반환된다.$_FILES어레이를 설정합니다.
function getMultiple_FILES() {
$_FILE = array();
foreach($_FILES as $name => $file) {
foreach($file as $property => $keys) {
foreach($keys as $key => $value) {
$_FILE[$name][$key][$property] = $value;
}
}
}
return $_FILE;
}
에러 요소를 포함한 foreach 루프를 실행하면
foreach($_FILES['userfile']['error'] as $k=>$v)
{
$uploadfile = 'uploads/'. basename($_FILES['userfile']['name'][$k]);
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$k], $uploadfile))
{
echo "File : ", $_FILES['userfile']['name'][$k] ," is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file : ", $_FILES['userfile']['name'][$k], " upload attack!\n";
}
}
다음과 같은 솔루션을 발견했습니다.
http://www.mydailyhacks.org/2014/11/05/php-multifile-uploader-for-php-5-4-5-5/
여러 입력과 AJAX 진행 표시줄을 추가할 수 있는 폼을 가진 준비된 PHP Multi File Upload Script입니다.서버에서 압축을 푼 후 바로 작동해야 합니다.
아래 스크립트를 사용하면 php를 사용하여 여러 파일을 쉽게 업로드할 수 있습니다.
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
이게 나한테 효과가 있었어.파일 업로드, 파일 이름 저장, 입력 필드부터 저장까지 추가 작업이 필요했고 여러 파일 이름당 하나의 레코드가 필요했습니다.serialize()를 사용하여 메인 SQL 쿼리에 추가하였습니다.
class addReminder extends dbconn {
public function addNewReminder(){
$this->exdate = $_POST['exdate'];
$this->name = $_POST['name'];
$this->category = $_POST['category'];
$this->location = $_POST['location'];
$this->notes = $_POST['notes'];
try {
if(isset($_POST['submit'])){
$total = count($_FILES['fileUpload']['tmp_name']);
for($i=0;$i<$total;$i++){
$fileName = $_FILES['fileUpload']['name'][$i];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = md5(uniqid());
$fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
$justFileName = $newFileName.'.'.$ext;
if($ext === 'pdf' || 'jpeg' || 'JPG'){
move_uploaded_file($_FILES['fileUpload']['tmp_name'][$i], $fileDest);
$this->fileName = array($justFileName);
$this->encodedFileNames = serialize($this->fileName);
var_dump($this->encodedFileNames);
}else{
echo $fileName . ' Could not be uploaded. Pdfs and jpegs only please';
}
}
$sql = "INSERT INTO reminders (exdate, name, category, location, fileUpload, notes) VALUES (:exdate,:name,:category,:location,:fileName,:notes)";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(':exdate', $this->exdate);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':location', $this->location);
$stmt->bindParam(':fileName', $this->encodedFileNames);
$stmt->bindParam(':notes', $this->notes);
$stmt->execute();
}
}catch(PDOException $e){
echo $e->getMessage();
}
}
}
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name))
{
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($error,"$file_name, ");
}
}
그리고 당신은 당신의 HTML 코드를 확인해야 합니다.
<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>
링크 연결:
PHP 싱글 파일 업로드와 다양한 기본 설명.
PHP 다중 파일 업로드 검증 소스 코드를 다운로드하려면 여기를 클릭하십시오.
PHP/jQuery ProgressBar 및 Validation을 사용하여 여러 파일 업로드(소스 코드를 다운로드하려면 여기를 클릭하십시오)
PHP에서 파일을 업로드하고 MySql 데이터베이스에 저장하는 방법(소스 코드를 다운로드하려면 여기를 클릭하십시오)
언급URL : https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php
'programing' 카테고리의 다른 글
| 이중 쿼리 없이 MySQL 페이지 번호 지정 (0) | 2022.11.05 |
|---|---|
| 도커가 도커파일을 사용하여 MariaDB에 사용자를 추가하지 않음 (0) | 2022.11.05 |
| 봄에 스케줄된 작업을 조건부로 활성화 또는 비활성화하려면 어떻게 해야 합니까? (0) | 2022.11.05 |
| MySQL 데이터베이스에서 열 이름을 포함한 Panda 데이터 프레임으로 데이터 가져오기 (0) | 2022.11.05 |
| 테이블의 일부에 대해 mysqldump를 사용하는 방법 (0) | 2022.11.05 |