728x90

■ 파일 업로드 다운로드

//html
<input type='file' class='reset_id' name='img' id='img11' />";
========================================================
//파일 업로드
//controller
$fileAttach = $this->upload('img');
if($fileAttach == "none" && $this->parameter['old_img'] != "") {
	$fileAttach = $this->parameter['old_img'];
}

//function controller
   // 업로드
	public function upload($file) {
		// 폴더생성
		@mkdir("attach/", 0777);

		$dir = "attach/"; //저장될 폴더 경로(끝에 '/'슬래시 꼭 붙여주세요...^^)
		chmod("$dir", 0777);

		$varName = $file; //이전 페이지에서 설정된 file 변수명
		$allowExt = "jpg,gif,png,jpeg,JPG,GIF,PNG,doc,DOC,docx,Docx,zip,ZIP,pdf,PDF"; //업로드 가능한 확장자 (,)콤마로 구분

		$prefix = time(); //파일명 앞에 자동으로 붙을 단어

		
		if($_FILES[$varName][name] && $_FILES[$varName][error] == 0) {
			// $dir 폴더가 지정됐고, 사용가능 한지 검사
			if(!$dir) {
				$this->goBack("업로드 폴더가 지정되지 않았습니다.");
				exit;
			}
			if(!is_writable($dir)) {
				$this->goBack("업로드 폴더 권한을 확인해 주세요.");
				exit;
			}

			// php.ini 파일에 설정된 upload_max_filesize 값을 이용해서 업로드 파일이 용량을 초과했는지검사
			$allowSize = intval(substr(ini_get(upload_max_filesize),0,-1)) * 1024 * 1024;
			if($allowSize < $_FILES[$varName][size]) {
				$this->goBack("파일 용량이 허용된 용량을 초과했습니다.");
				exit;
			}

			// 정상적인 방법으로 업로드 된 파일인지 검사 후 정상이면 파일 업로드 처리
			if(is_uploaded_file($_FILES[$varName][tmp_name])) {
				// 확장자 검사
				$ext = substr(strrchr($_FILES[$varName][name],"."),1);
				if($ext) {
					$allow = explode(",",$allowExt);
					if(is_array($allow)) $check = in_array($ext,$allow);
					else $check = ($ext == $allow) ? true : false;
				}
		
				if(!$ext || !$check) {
					$this->goBack("업로드 불가능한 확장자 입니다.");
					exit;
				}

				// 파일명 생성 및 존재하는지 검사
				// $newfile = md5($prefix.$_FILES[$varName][name]).".".$ext;
				$newfile = $prefix.$_FILES[$varName][name];
				$newfile2 = iconv("UTF-8", "EUC-KR", $newfile );

				if(file_exists($dir.$newfile2)) {
					$this->goBack("같은이름의 화일이 있습니다. 화일명을 변경하고 업로드 하시기 바랍니다.");
					exit;
				} 
 				//$newfile = iconv("UTF-8", "EUC-KR", $newfile );
 
				// $dir 에 파일 저장
				if(!move_uploaded_file($_FILES[$varName][tmp_name], $dir.$newfile2)) {
					$this->goBack("파일 업로드에 실패했습니다.");
					exit;
				}
 
				if(!chmod($dir.$newfile2,0707)) {
					$this->goBack("퍼미션변경에 실패했습니다.");
					exit;
				}
 				//$newfile = iconv("EUC-KR", "UTF-8", $newfile );
				$newfile = urlencode($newfile);
				$newfile = urldecode($newfile);

				return $newfile;
			}
		} else {
			return "none";
		}
	} 

================================================================================
//파일 미리보기(새창)
<a href='attach/"+ json[i].img_view +"' target='_blank' ><span style='font-size:20px;'>"+ (json[i].img_view).substr(0,10) +"</span></a>

//파일 미리보기(view)
<td>
	 <div id="upDiv" style="display:none">
         <img id="uploadImg" src="" style="width:30px; height:30px;" style="display:none"/>
     </div>
	 <input type="file" name="img[]" id="img" />
</td>

if(json.img != "none" && json.img != null && json.img != "") {
	$("#upDiv").css("display","block");
	$("#uploadImg").attr("src","attach/" + json.img);
	$("#old_img").val(json.img);
} else {
	$("#upDiv").css("display","none");
}

//파일 다운
<a href='attach/excel_sample/이미지.jpg'>파일명</a>
 

 

■ 엑셀업로드 , 엑셀 다운로드

01. https://github.com/PHPOffice/PHPExcel 사이트에 접속하여 PHP Excel 라이브러리 파일을 다운받고

압축을 해제하여 프로젝트 라이브러리 폴더에 넣는다.

PHPExcel 라이브러리 Excel 파일 다운받기

<?php

include "./PHPExcel-1.8/Classes/PHPExcel.php";
$objPHPExcel = new PHPExcel();

$arrTwice = array();
$arrTwice[1] = array("name" => "나연", "position" => "리드보컬, 리드댄서", "birthday" => "09월 22일");
$arrTwice[2] = array("name" => "정연", "position" => "리드보컬", "birthday" => "11월 01일");
$arrTwice[3] = array("name" => "모모", "position" => "서브보컬, 메인댄서, 서브래퍼", "birthday" => "11월 09일");
$arrTwice[4] = array("name" => "사나", "position" => "서브보컬", "birthday" => "12월 29일");
$arrTwice[5] = array("name" => "지효", "position" => "리더, 메인보컬", "birthday" => "02월 01일");
$arrTwice[6] = array("name" => "미나", "position" => "서브보컬, 메인댄서, 서브래퍼", "birthday" => "03월 24일");
$arrTwice[7] = array("name" => "다현", "position" => "리드래퍼, 서브보컬", "birthday" => "05월 28일");
$arrTwice[8] = array("name" => "채영", "position" => "메인래퍼, 서브보컬", "birthday" => "04월 23일");
$arrTwice[9] = array("name" => "쯔위", "position" => "서브보컬, 리드댄서", "birthday" => "06월 14일");

$objPHPExcel -> setActiveSheetIndex(0)
-> setCellValue("A1", "NO.")
-> setCellValue("B1", "이름")
-> setCellValue("C1", "포지션")
-> setCellValue("D1", "생일");

$count = 1;
foreach($arrTwice as $key => $val) {
	$num = 1 + $key;
	$objPHPExcel -> setActiveSheetIndex(0)
	-> setCellValue(sprintf("A%s", $num), $key)
	-> setCellValue(sprintf("B%s", $num), $val['name'])
	-> setCellValueExplicit(sprintf("C%s", $num), $val['position'])
	-> setCellValue(sprintf("D%s", $num), $val['birthday']);
	$count++;
}

// 가로 넓이 조정
$objPHPExcel -> getActiveSheet() -> getColumnDimension("A") -> setWidth(6);
$objPHPExcel -> getActiveSheet() -> getColumnDimension("B") -> setWidth(12);
$objPHPExcel -> getActiveSheet() -> getColumnDimension("C") -> setWidth(30);
$objPHPExcel -> getActiveSheet() -> getColumnDimension("D") -> setWidth(15);

// 전체 가운데 정렬
$objPHPExcel -> getActiveSheet() -> getStyle(sprintf("A1:D%s", $count)) -> getAlignment() -> setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

// 전체 테두리 지정
$objPHPExcel -> getActiveSheet() -> getStyle(sprintf("A1:D%s", $count)) -> getBorders() -> getAllBorders() -> setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

// 타이틀 부분
$objPHPExcel -> getActiveSheet() -> getStyle("A1:D1") -> getFont() -> setBold(true);
$objPHPExcel -> getActiveSheet() -> getStyle("A1:D1") -> getFill() -> setFillType(PHPExcel_Style_Fill::FILL_SOLID) -> getStartColor() -> setRGB("CECBCA");
// $objPHPExcel -> getActiveSheet() -> getRowDimension(1) -> setRowHeight(23);

// 내용 지정
$objPHPExcel -> getActiveSheet() -> getStyle(sprintf("A2:D%s", $count)) -> getFill() -> setFillType(PHPExcel_Style_Fill::FILL_SOLID) -> getStartColor() -> setRGB("F4F4F4");

// 시트 네임
$objPHPExcel -> getActiveSheet() -> setTitle("트와이스");

// 첫번째 시트(Sheet)로 열리게 설정
$objPHPExcel -> setActiveSheetIndex(0);

// 파일의 저장형식이 utf-8일 경우 한글파일 이름은 깨지므로 euc-kr로 변환해준다.
$filename = iconv("UTF-8", "EUC-KR", "트와이스_TWICE");


// 브라우저로 엑셀파일을 리다이렉션
header("Content-Type:application/vnd.ms-excel");
header("Content-Disposition: attachment;filename=".$filename.".xls");
header("Cache-Control:max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel5");
$objWriter -> save("php://output");

?>
728x90

+ Recent posts