테스트 사이트 - 개발 중인 베타 버전입니다

파일선택 버튼으로 이미지 업로드 시 화면이동 하지 않고 업로드 하기 채택완료

Sssuj 4년 전 조회 2,105

https://seoneu.tistory.com/29 제가 참고하여 사용한 링크입니다.

 

파일선택 버튼을 클릭해서 파일을 선택한 후 새로운 파일 업로드 버튼을 누르면 다른 화면으로 넘어가 업로드가 진행되는데 다른화면으로 이동하지 않고 업로드 진행 후 결과만 alert로 띄워주고 싶습니다. 

 

혹시 참고할만한 사이트가 있다면 링크 부탁드립니다.

 

ajax를 이용하여 구현해보려고 했는데 입력받은 파일을 넘겨줄 방법을 찾지 못해 막힌 상태입니다.

</strong></p>

<p><form name="reqform" enctype="multipart/form-data">

               <center>

                  <div class="filebox">

                     <img src="./basicImg/backImg.jpg" height="130" width="160" id="showleftImg">

                     <p class="explanation2">왼쪽에 삽입할 이미지를 선택해주세요.</p>

                     <div class="file-upload preview-image">

                        <input type="button" value="기존이미지 선택" class="button_img" onclick="openLeftPopup()"/>

                        <input class="fileButton" type="file" name="imgFile" accept="image/*"/>

                        


                     </div>

                     <input type="hidden" id="leftImg" class="leftImg" value="">

                     <input type="submit" value="새로운 파일 업로드" class="button_img buttonNewfile" id="LeftfileButton" data-qa_file=""/>

                  </div>

                  <script>

                     $('input[id=LeftfileButton]').change(function() {

                     var qa_file = $(this).data("qa_file");

                     

                     $.ajax({

                        url: "fileUploadResult2.php",

                        type: "POST",

                        data: {

                           "qa_file": qa_file

                        },

                        dataType: "json",

                        async: false,

                        cache: false,

                        success: function(data, textStatus) {

                           class_id=data.Competition;

                           alert("dd");

                        }

                     });

                     }); 

                  </script>

               </center>

            </form></p>

<p><strong>

 

다른 화면으로 넘어가 업로드하는 코드입니다.

</strong></p>

<p><form name="reqform" method="post" action="fileUploadResult.php" enctype="multipart/form-data">

               <center>

                  <div class="filebox">

                     <img src="./basicImg/backImg.jpg" height="130" width="160" id="showleftImg">

                     <p class="explanation2">왼쪽에 삽입할 이미지를 선택해주세요.</p>

                     <div class="file-upload preview-image">

                        <input type="button" value="기존이미지 선택" class="button_img" onclick="openLeftPopup()"/>

                        <input class="fileButton" type="file" name="imgFile" accept="image/*" id="LeftfileButton" />

                        


                     </div>

                     <input type="hidden" id="leftImg" class="leftImg" value="">

                     <input type="submit" value="새로운 파일 업로드" class="button_img buttonNewfile" />

                  </div>

               </center>

            </form></p>

<p><strong>

 

넘어가는 화면의 코드입니다.

</strong></p>

<p><strong><?php 

$tempFile = $_FILES['imgFile']['tmp_name'];

if($tempFile){

// 파일타입 및 확장자 체크

$fileTypeExt = explode("/", $_FILES['imgFile']['type']);</strong></p>

<p><strong>// 파일 타입 

$fileType = $fileTypeExt[0];</strong></p>

<p><strong>// 파일 확장자

$fileExt = $fileTypeExt[1];</strong></p>

<p><strong>// 확장자 검사

$extStatus = false;</strong></p>

<p><strong>switch($fileExt){

    case 'jpeg':

    case 'jpg':

    case 'gif':

    case 'bmp':

    case 'png':

        $extStatus = true;

        break;

    

    default:

        echo "<script>alert('이미지 전용 확장자(jpg, bmp, gif, png)외에는 사용이 불가합니다.');</script>"; 

        exit;

        break;

}</strong></p>

<p><strong>// 이미지 파일이 맞는지 검사. 

if($fileType == 'image'){

    // 허용할 확장자를 jpg, bmp, gif, png로 정함, 그 외에는 업로드 불가

    if($extStatus){

        // 임시 파일 옮길 디렉토리 및 파일명

        $resFile = "./img/{$_FILES['imgFile']['name']}";

        // 임시 저장된 파일을 우리가 저장할 디렉토리 및 파일명으로 옮김

        $imageUpload = move_uploaded_file($tempFile, $resFile);</strong></p>

<p><strong>        $conn = mysqli_connect("localhost", "lsj", "1234" , "phptest");

        mysqli_query($conn,'SET NAMES utf8');

        $img_name = $_FILES['imgFile']['name'];

        $img_url = $resFile;

        $statement = mysqli_prepare($conn, "INSERT INTO img VALUES (?,?)");

        mysqli_stmt_bind_param($statement, "ss", $img_name, $img_url);

           mysqli_stmt_execute($statement);

        

        // 업로드 성공 여부 확인

        if($imageUpload == true){

            echo "<script>alert('파일이 정상적으로 업로드 되었습니다.');</script>";

        }else{

            echo "<script>alert('파일 업로드에 실패하였습니다.');</script>";

        }

    }    // end if - extStatus

        // 확장자가 jpg, bmp, gif, png가 아닌 경우 else문 실행

    else {

        echo "<script>alert('파일 확장자는 jpg, bmp, gif, png 이어야 합니다.');</script>";

        exit;

    }    

}    // end if - filetype

    // 파일 타입이 image가 아닌 경우 

else {

    echo "<script>alert('이미지 파일이 아닙니다.');</script>";

    exit;

}</strong></p>

<p><strong>}

else{

    echo "<script>alert('새로 업로드할 이미지를 파일 선택 버튼을 클릭하여 선택해주세요.');</script>";

}

?></strong></p>

<p><strong>

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

답변 2개

채택된 답변
+20 포인트
로그인 후 평가할 수 있습니다

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

일단 맞을까 아니면 넘어가세요...

코드 예들면요.

HTML, PHP

<div class="filebox"> <label for="file">업로드</label> <input type="file" id="file"> <input class="upload-name" value="파일선택"> </div></span></span></p>

<p><span style="font-size:10pt;"><span style="font-family:맑은 고딕;">

 

CSS</span></span></p>

<pre tabindex="0">
<span style="font-family:맑은 고딕;"><span style="font-size:10pt;"><code data-lang="css" id="actual-css-code">.filebox input[type="file"] {
  position: absolute;
  width: 0;
  height: 0;
  padding: 0;
  overflow: hidden;
  border: 0;
}

.filebox label {
  display: inline-block;
  padding: 10px 20px;
  color: #999;
  vertical-align: middle;
  background-color: #fdfdfd;
  cursor: pointer;
  border: 1px solid #ebebeb;
  border-radius: 5px;
}

/* named upload */
.filebox .upload-name {
  display: inline-block;
  height: 35px;
  font-size:18px; 
  padding: 0 10px;
  vertical-align: middle;
  background-color: #f5f5f5;
  border: 1px solid #ebebeb;
  border-radius: 5px;

}</code></span></span></pre>

<p><span style="font-family:맑은 고딕;"><span style="font-size:10pt;">

 

JS</span></span></p>

<pre tabindex="0">
<span style="font-size:10pt;"><span style="font-family:맑은 고딕;"><code data-lang="javascript" id="actual-js-code">$("#file").on('change',function(){
  var fileName = $("#file").val();
  $(".upload-name").val(fileName);
});</code></span></span></pre>

<p><span style="font-size:10pt;"><span style="font-family:맑은 고딕;">

로그인 후 평가할 수 있습니다

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

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

로그인