채택완료

영카트 상세페이지에서 일반파일 다운로드

2025-01-08 (수) 12:12:09 3,166

영카트의 제품상세페이지에서 해당제품의 1.카달로그(pdf), 2.제품설명서(pdf), 3.도면((pdf) 파일(이미지가아닌 일반파일; pdf 나 hwp)을 다운로드 할 수 있도록 하려고 작업중입니다.


상품등록페이지의 여분필드를 이용하여 작업중인데 쉽지가 않네요 ㅠㅠ

===========================

1. 파일 업로드 : 상품등록페이지 itemform.php 의 여분필드를 이용

2. 업로드한 파일의 처리 : itemformupdate.php

3. 파일 다운로드 : 해당 상품 상세페이지 item.form.skin.php

===========================

이런 형식으로 다른 분들의 글들을 참고하여 작업을 하고 있는데 하면 할 수록 감을 못잡고 더 난감해지고 있습니다. ㅠㅠ

고수님들의 조언 부탁드려요 ㅠㅠ

itemform.php

Copy
<tr>
    <th scope="row">카달로그</th>
    <td class="td_extra">
      <input type="file" name="it_1" id="it_1">
        <?php $it_1 = G5_DATA_PATH.'/item/'.$it['it_1']; ?>
            <label for="it_1_del"><span class="sound_only">파일 1 </span>파일삭제</label>
            <input type="checkbox" name="it_1_del" id="it_1_del" value="1">
            


    </td>
    <td class="td_grpset"></td>
    
</tr>
 

item.form.skin.php

Copy
<table class="sit_ov_tbl">
<colgroup>
<col class="grid_3">
<col>
</colgroup>
<tbody>
<!-- <?php if ($it['it_1']) { ?> -->
<tr>
    <th scope="row">카달로그</th>
    <td><?php echo $it['it_1']; ?></td>
</tr>
<!-- <?php } ?> -->


<!-- <?php if ($it['it_2']) { ?> -->
<tr>
    <th scope="row">제품 사용 설명서</th>
    <td><?php echo $it['it_2']; ?></td>
</tr>
<!-- <?php } ?> -->


<!-- <?php if ($it['it_3']) { ?> -->
<tr>
    <th scope="row">3D 도면</th>
    <td><?php echo $it['it_3']; ?></td>
</tr>
<!-- <?php } ?> -->
</tbody>
</table>
 

답변 3개 / 댓글 2개

채택된 답변
+20 포인트

싱품 이미지 업로드와 여분 필드 파일 업로드의 주요 차이는 저장 경로와 DB 저장 방식.

상품 이미지는 기본적으로 지정된 경로(/data/item/)에 저장되며,

이를 여분 필드와 동일하게 활용할 수 있음.

추가로, 업로드 파일 이름을 처리하거나 중복 파일 이름을 방지하는 로직이 필요.

단순히 <a href="파일경로"> 링크로 제공하면

PDF 파일은 다운로드되지 않고 브라우저에서 열리는 경우가 많습니다.

따라서 강제 다운로드 기능을 구현하려면 PHP로 처리하는 별도의 스크립트가 필요.

업로드 처리(itemformupdate.php):

Copy
$upload_path = G5_DATA_PATH . '/item/';

if ($_FILES['it_1']['name']) {
    $filename = time() . '_' . basename($_FILES['it_1']['name']); // 고유한 파일명 생성
    $filepath = $upload_path . $filename;

    // 파일 확장자 및 MIME 유형 검증
    $allowed_extensions = ['pdf', 'hwp'];
    $file_extension = pathinfo($filename, PATHINFO_EXTENSION);

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $_FILES['it_1']['tmp_name']);
    finfo_close($finfo);

    if (!in_array($file_extension, $allowed_extensions) || !in_array($mime_type, ['application/pdf', 'application/x-hwp'])) {
        die("허용되지 않은 파일 형식입니다.");
    }

    // 파일 업로드
    if (move_uploaded_file($_FILES['it_1']['tmp_name'], $filepath)) {
        sql_query("UPDATE {$g5['g5_shop_item_table']} SET it_1 = '{$filename}' WHERE it_id = '{$it_id}'");
    }
}

강제 다운로드 처리 (custom_download.php):

Copy
<?php
$file = basename($_GET['file']); // 디렉토리 트래버설 방지
$filepath = G5_DATA_PATH . '/item/' . $file;

if (file_exists($filepath)) {
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . rawurlencode(basename($filepath)) . "\"");
    header("Content-Length: " . filesize($filepath));
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Pragma: no-cache");
    readfile($filepath);
} else {
    echo "파일이 존재하지 않습니다.";
}
exit;
?>

다운로드 링크(item.form.skin.php):

Copy
<td>
    <a href="/bbs/custom_download.php?file=<?php echo urlencode($it['it_1']); ?>">카달로그 다운로드</a>
</td>

답변에 대한 댓글 2개

FTP로 확인을 해보니 서버에 파일은 업로드가 되네요^^
감사합니다.
그런데 상품등록페이지 itemform.php와
상세페이지인 item.form.skin.php에 업로드된 파일 등의 표시는 안되네요ㅠㅠ

아마도 제가 코딩한 부분이 문제가 있는 듯요 ㅠㅠ
이 부분만 해결되면 좋은 텐데요 ㅠㅠ

혹시 이부분에 대해 알고 계시면 도와주세요ㅠㅠ
업로드된 파일의 데이터가 데이터베이스에 제대로 저장되지 않았거나,
해당 데이터를 불러오는 코드에서 오류가 있을 가능성이 있습니다.

itemformupdate.php에서 파일 업로드 후 데이터베이스 업데이트가 올바르게 이루어졌는지 확인.
if ($_FILES['it_1']['name']) {
$filename = time() . '_' . basename($_FILES['it_1']['name']);
$filepath = G5_DATA_PATH . '/item/' . $filename;

if (move_uploaded_file($_FILES['it_1']['tmp_name'], $filepath)) {
sql_query("UPDATE {$g5['g5_shop_item_table']} SET it_1 = '{$filename}' WHERE it_id = '{$it_id}'");
}
}
- $g5['g5_shop_item_table']와 $it_id 변수가 올바르게 설정되어 있는지 확인.
- 데이터베이스에 업로드된 파일 이름이 저장되었는지 직접 확인.

item.form.skin.php에서 $it['it_1'] 변수가 정확히 데이터베이스 값을 가져오는지 확인.
<td>
<a href="/bbs/custom_download.php?file=<?php echo urlencode($it['it_1']); ?>">카달로그 다운로드</a>
</td>
- $it 배열이 비어있거나 it_1 키가 없는 경우,
데이터베이스에서 값이 제대로 조회되지 않았을 가능성이 있음.

MySQL 클라이언트나 phpMyAdmin을 이용하여
상품 테이블에서 해당 it_id에 대해 it_1 열에 저장된 값이 있는지 확인.
SELECT it_1 FROM g5_shop_item_table WHERE it_id = '상품ID';
2025-03-26 (수) 18:49:09

답변 감사합니다. 고수님들의 의견을 참고하여 잘 해결하였습니다.

감사합니다.

업로드는 상품이미지 업로드 부분을 참조해서 하시면 되구요.

다운로드는 링크만 하면 자동으로 다운로드가 됩니다.

<td><a href="<?php echo $it['it_1']; ?>">다운로드</a></td>

브라우저에서 열리는걸 방지하려면,

/bbs/download.php  파일을 참조해서 만들면 됩니다.

답변을 작성하려면 로그인이 필요합니다.