중국어 파일 이름으로 업로드되었으므로 PHP가 데이터베이스에서 업로드 된 파일을 다운로드하지 못했습니다.

청푸

실례합니다. 사용자가 문서 (pdf)를 mysql 데이터베이스에 업로드 할 수있는 웹 사이트를 구축하고 있습니다.

업로드 및 다운로드 php 페이지를 작성했기 때문에 파일 (pdf)을 업로드하고 영문 이름의 파일을 성공적으로 다운로드 할 수 있었지만 이름에 중국어 단어가 포함 된 파일은 다운로드하지 못했습니다.

좀 더 구체적으로 말하면 중국어 파일을 다운로드 할 수 있지만 열 수는 없습니다. 파일이 손상되었음을 보여줍니다.

다음은 내 업로드 PHP 페이지 코드의 일부입니다.

        $connect = mysqli_connect("localhost", "root", "password", "table");
        if(mysqli_connect_errno($connect))//check connection
        {
               /*show error message and die*/
        }
        //set client character set to 'utf8'
        mysqli_set_charset($connect, "utf8");

        $fileName = mysqli_real_escape_string($connect, $name);
        $filePath = mysqli_real_escape_string($connect, $tmp_name);
        $fileSize = mysqli_real_escape_string($connect, $size);
        $fileType = mysqli_real_escape_string($connect, $type);
        $content = mysqli_real_escape_string($connect, file_get_contents($tmp_name));

        $filePath = addslashes($filePath);

        if(!get_magic_quotes_gpc())
        {
            $fileName = addslashes($fileName);
        }

        $teamName = $_COOKIE['teamName'];
        $reportQuery = "UPDATE uploadedreport SET name='$fileName', type='$fileType', size='$fileSize', content='$content' WHERE team='$teamName'";



        uploadFileQuery($connect, $reportQuery, $fileName);
        mysqli_close($connect);

게다가 다운로드 PHP 페이지 코드의 또 다른 부분은 다음과 같습니다.

    $teamName = $_COOKIE['teamName'];
    $downloadReportQuery = "SELECT name, type, size, content FROM uploadedreport WHERE team='$teamName'";


    $result = mysqli_query($connect, $downloadReportQuery);
    if($result == false)
    {
      /*alert error message and die*/
    }

    $row = mysqli_fetch_array($result);

    header("Content-length:$row[size]");
    header("Content-type:$row[type]");
    header("Content-Transfer-Encoding: binary");
    header("Content-Disposition: attachment; filename=$row[name]");//Tells the browser to save this downloaded file under the specified name

    echo $row["content"];
    mysqli_free_result($result);
    mysqli_close($connect);

뭐가 잘못 됐나요? 나는 며칠 동안이 문제로 인해 방해를 받고있다.

당신의 도움을 주셔서 감사합니다!

Notepad ++를 사용하여 손상된 다운로드 된 pdf 파일 열기 : 다운로드 한 pdf의 일부

업로드 페이지의 HTML 코드가 있습니다.

<div id="pageDiv">
    <section id="mainSection">
        <div id="mainDiv">
            <form action="upload.php" method="post" enctype="multipart/form-data">
                <table id="mainTable">
                    <tbody>
                        <tr>
                            <td class="headColumn paragraphTitle"><label for="uploadedReport">競賽報告上傳</label></td>
                            <td><span class="hint"><span id="reportDueText"></span>截止</span></td>
                        </tr>
                        <tr>
                            <td><div id="uploadedReportDiv"><input id="uploadedReport" name="uploadedReport" type="file" required /></div></td>
                            <td><span class="hint">請以pdf格式上傳</span></td>
                        </tr>
                        <tr>
                            <td class="headColumn paragraphTitle"><label for="uploadedBriefing">競賽簡報上傳</label></td>
                            <td><span class="hint"><span id="briefingDueText"></span>截止</span></td>
                        </tr>
                        <tr>
                            <td><div id="uploadedBriefingDiv"><input id="uploadedBriefing" name="uploadedBriefing" type="file" required /></div></td>
                            <td><span class="hint">請以ppt, pptx 或pdf格式上傳</span></td>
                        </tr>
                        <tr><td colspan="2"><input id="uploadButton" type="submit" value=""/></td></tr>
                        <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                        <tr>
                            <td class="headColumn paragraphTitle">檢視已上傳檔案</td>
                            <td><a id="downloadUploadedFile" href="#">未上傳</a></td><!-- link to download file. If user has uploaded it, href will be changed by the javascript function afterUploaded -->
                        </tr>
                    </tbody>
                </table>
            </form>
        </div>
    </section>
</div>

다른 쪽은 업로드 페이지의 내 자바 스크립트 코드입니다.

<script>
$(document).ready(
    function()
    {
        setDateText(reportDue, "reportDueText");
        setDateText(briefingDue, "briefingDueText");

        afterUploaded();

        if(now > reportDue)
        {
            $("#uploadedReportDiv").hide();
            $("#uploadedReport").attr("required", false);
        }

        if(now > briefingDue || now <= reportDue)
        {
            $("#uploadedBriefingDiv").hide();
            $("#uploadedBriefing").attr("required", false);
        }

        $("form").submit(
            function()
            {
                var validateReport = false;
                var validateBriefing = false;

                if($("#uploadedReportDiv").is(":visible") && $("#uploadedReport").val().length > 0)
                {
                    validateReport = validateUploadedFile($("#uploadedReport").val(), "pdf");
                }
                else if(!$("#uploadedReportDiv").is(":visible"))
                    validateReport = true;

                if($("#uploadedBriefingDiv").is(":visible") && $("#uploadedBriefing").val().length > 0)
                    validateBriefing = validateUploadedFile($("#uploadedBriefing").val(), "pdf ppt pptx");
                else if(!$("#uploadedBriefingDiv").is(":visible"))
                    validateBriefing = true;


                if(!validateReport)
                    alert("檔案格式錯誤,請上傳pdf格式檔案。");//alert upload wrong file format
                if(!validateBriefing)
                    alert("檔案格式錯誤,請上傳ppt, pptx 或pdf格式檔案。");//alert upload wrong file format

                return (validateReport && validateBriefing);
            }
        );
    }
);

function setDateText(date, objectId)
{
    var dateText = (date.getFullYear()-1911) + "/" + (date.getMonth()+1) + "/" + (date.getDate());
    $("#" + objectId).text(dateText);
}

function validateUploadedFile(filename, validExtensions)
{
    var splitedArray = filename.split(".");
    var fileExtension = splitedArray[splitedArray.length-1];

    if(validExtensions.indexOf(fileExtension) == -1)
        return false;
    else
        return true;
}

function afterUploaded()
{
    if($.cookie("isUploaded"))
    {
        $("#downloadUploadedFile").attr("href", "download.php").text("下載檔案(" + $.cookie("uploadedFileName") + ")");
    }
}
</script>

감사합니다!

앙투안 밀 코프

귀하의 답변에 따르면 DB에서 파일을 읽은 후 파일이 동일하지 않으므로 분명히 뭔가 잘못되었습니다.

MySQL이 바이너리 데이터 유형을 지원하는 것은 사실입니다. 그러나 할 수 있다고해서 그렇게해야한다는 것을 의미하지는 않습니다. MySQL은 한 번에 결과를 클라이언트에 보냅니다. 결과적으로 2 진 데이터로 결과 세트를 구문 분석하는 모든 애플리케이션은 처리되기 전에 각 행이 도착할 때까지 기다려야합니다. 또한 MySQL에 바이너리 데이터를 저장하는 것은 실질적인 이점이 없습니다.

바이너리 데이터에 대한 더 나은 접근 방식은 해당 데이터를 파일 시스템에 저장하고 해당 파일에 대한 포인터를 MySQL에 저장하는 것입니다. 이 접근 방식을 사용하면 결과 집합을 처리하는 동안 실제로 백그라운드 스레드에서 이진 데이터를 스트리밍 할 수 있습니다.

이 팁은 바이너리 데이터에만 적용되지 않습니다. 모든 종류의 대형 데이터 개체에 적용됩니다. 바이너리 데이터를 괴롭히는 성능 문제는 문자 데이터도 괴롭 힙니다. 즉, 결과 집합의 모든 부분을 연속적으로 읽습니다. 이진 데이터는 일반적으로 크기가 크기 때문에 더 많은주의를 기울일 것입니다. 큰 문자 데이터에서도 똑같이 문제를 알 수 있습니다. 파일 시스템에 큰 문자 데이터를 저장할 때의 성능 이점과 데이터베이스의 해당 데이터를 검색하는 기능을 비교해 볼 필요가 있습니다.

그러나 파일을 DB에 저장하려는 경우 BLOB 유형 필드를 사용하십시오. 여기 에서 관련 매뉴얼 페이지를 참조하십시오.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관