2013-10-27 3 views
58

양식을 사용하지 않고 jstar를 사용하여 POST 메서드를 사용하여 <input type="file">의 파일/파일을 'upload.php'로 보낼 수 있습니까? 입력 태그가 양식 태그 안에 없습니다. 그것은 개별적으로 나타냅니다. 그래서 'ajaxForm'이나 'ajaxSubmit'과 같은 jQuery 플러그인을 사용하고 싶지 않습니다.양식없이 파일 업로드

+0

이 시도 : http://www.uploadify.com/을하지만 플래시를 사용 번역. 어서, 네 바위를 던져. HTML5 버전이 양식없이 작동하는지 확실하지 않습니다. 아마 그래도 될지 모르지만. –

+0

Arrr .... HTML 5에서 작동해야한다고 말하고 싶습니다. 그러나 플랫폼 호환성 문제로 인해 몇 년이 넘은 브라우저가 등장 할 것입니다. 양식을 만들 때 해가되는 것, 또는 그물에서 양식을 동적으로 생성하는 것은 무엇입니까? – Yitzhak

답변

1

이 puglin simpleUpload, 필요없이 양식

HTML을 시도해보십시오 그렇게 아주 기본적인 방법

$('#simpleUpload').simpleUpload({ 
    url: 'upload.php', 
    trigger: '#enviar', 
    success: function(data){ 
    alert('Envio com sucesso'); 

    } 
}); 
+0

불행히도, 작동하지 않습니다 – alerya

9

주둔에 this tutorial, 여기 :

<input type="file" name="arquivo" id="simpleUpload" multiple > 
<button type="button" id="enviar">Enviar</button> 

자바 스크립트를

$('your_trigger_element_selector').on('click', function(){  
    var data = new FormData(); 
    data.append('input_file_name', $('your_file_input_selector').prop('files')[0]); 
    // append other variables to data if you want: data.append('field_name_x', field_value_x); 

    $.ajax({ 
     type: 'POST',    
     processData: false, // important 
     contentType: false, // important 
     data: data, 
     url: your_ajax_path, 
     dataType : 'json', 
     // in PHP you can call and process file in the same way as if it was submitted from a form: 
     // $_FILES['input_file_name'] 
     success: function(jsonData){ 
      ... 
     } 
     ... 
    }); 
}); 

당신은 POST 요청하여 데이터를 제출 FormData을 사용할 수 있습니다

62

처리 적절한 오류를 추가하는 것을 잊지 마십시오. 당신은 (URL, 방법 및 매개 변수 데이터 등) 요청 설정을 알고있는 한, 아약스 요청을하는 양식을 사용할 필요가 없습니다

var myFormData = new FormData(); 
myFormData.append('pictureFile', pictureInput.files[0]); 

$.ajax({ 
    url: 'upload.php', 
    type: 'POST', 
    processData: false, // important 
    contentType: false, // important 
    dataType : 'json', 
    data: myFormData 
}); 

: 다음은 간단한 예입니다.

+0

이 IMHO가 최선의 해결책이지만 다른 선택은 내부의

+0

네, 맞습니다. 오래된 브라우저는 파일을 업로드하기 위해 FormData와 ajax를 지원하지 않으며 해당 브라우저에서 iframe을 대체 브라우저로 사용하는 경우 해결책을 제공합니다. –

+6

'processData : false'와'contentType : false'를 설정 객체에 추가하는 것을 잊지 마십시오. 그렇지 않으면 Uncaught TypeError를받을 것입니다 : 불법 호출 – jsmiff

2

죄송합니다 그 남자하지만 AngularJS는 간단하고 우아한 솔루션을 제공합니다. (가) 파일이 Request.Files 수집 및 반환에있는 업로드 된 저장

ngApp.controller('ngController', ['$upload', 
 
function($upload) { 
 

 
    $scope.Upload = function($files, index) { 
 
    for (var i = 0; i < $files.length; i++) { 
 
     var file = $files[i]; 
 
     $scope.upload = $upload.upload({ 
 
     file: file, 
 
     url: '/File/Upload', 
 
     data: { 
 
      id: 1 //some data you want to send along with the file, 
 
      name: 'ABC' //some data you want to send along with the file, 
 
     }, 
 

 
     }).progress(function(evt) { 
 

 
     }).success(function(data, status, headers, config) { 
 
      alert('Upload done'); 
 
     } 
 
     }) 
 
    .error(function(message) { 
 
     alert('Upload failed'); 
 
    }); 
 
    } 
 
}; 
 
}]);
.Hidden { 
 
    display: none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div data-ng-controller="ngController"> 
 
    <input type="button" value="Browse" onclick="$(this).next().click();" /> 
 
    <input type="file" ng-file-select="Upload($files, 1)" class="Hidden" /> 
 
</div>

서버 측에 나는 액션이있는 MVC 컨트롤러가 : 여기

내가 사용하는 코드입니다 JsonResult. 당신이 사용하는 경우 당신이하지 않으면 ... 미안 짝을

+0

이 스 니펫에는 많은 오류가 있습니다. –

+0

$ upload 지시문이 작동하지 않아 Downvoted – NicoJuicy

9

:-) 여기에 모든 답은 여전히 ​​FormData API을 사용하는

AngularJS와,이 밖으로 시도. 양식없는 양식 파일 업로드와 같습니다. 당신은 또한이 같은 xmlHttpRequest를 사용하여 POST 요청의 본문 안에 내용으로 직접 파일을 업로드 할 수 있습니다 :

var xmlHttpRequest = new XMLHttpRequest(); 

var file = ...file handle... 
var fileName = ...file name... 
var target = ...target... 
var mimeType = ...mime type... 

xmlHttpRequest.open('POST', target, true); 
xmlHttpRequest.setRequestHeader('Content-Type', mimeType); 
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"'); 
xmlHttpRequest.send(file); 

Content-TypeContent-Disposition 헤더는 우리가 (MIME 형식 및 파일 이름)을 보내는 것을 설명하는 데 사용됩니다.

나는 비슷한 대답을 게시했습니다. here.

6

1 단계 : HTML 코드를 삽입 할 HTML 페이지를 만듭니다.

2 단계 : HTML 코드 페이지 하단 (바닥 글)에서 Javascript를 만들고 Jquery Code를 Script 태그에 넣습니다.

3 단계 : PHP 파일 및 PHP 코드 사본을 작성하십시오. 후 JQuery 코드 $.ajax에 코드 URL을 하나의 PHP 파일 이름에 적용됩니다.

JS

//$(document).on("change", "#avatar", function() { // If you want to upload without a submit button 
$(document).on("click", "#upload", function() { 
    var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field 
    var form_data = new FormData(); // Creating object of FormData class 
    form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data 
    form_data.append("user_id", 123) // Adding extra parameters to form_data 
    $.ajax({ 
    url: "/upload_avatar", // Upload Script 
    dataType: 'script', 
    cache: false, 
    contentType: false, 
    processData: false, 
    data: form_data, // Setting the data attribute of ajax with file_data 
    type: 'post', 
    success: function(data) { 
     // Do something after Ajax completes 
    } 
    }); 
}); 

HTML

<input id="avatar" type="file" name="avatar" /> 
<button id="upload" value="Upload" /> 

print_r($_FILES); 
print_r($_POST); 
+1

코드에 대한 설명/설명을 추가하십시오. – kvorobiev

+0

'','after :'type : 'post'' – user3284463

+1

내 날을 만들었습니다. 감사합니다. – shekhardtu