2016-01-21 128 views
0

在填寫表單時,我希望我的用戶預覽他們剛在文件輸入字段中選擇的內容。 爲此,我試圖避免任何類型的插件或其他軟件(jQuery除外)。通過AJAX上傳文件輸入

這是我得到的,經過一些互聯網研究:

$("#file-upload").change(function() { 
    var formData = new FormData($("#editForm")[0]); 
    $.ajax({ 
     url: 'script.php', //Server script to process data 
     type: 'POST', 
     xhr: function() { // Custom XMLHttpRequest 
      var myXhr = $.ajaxSettings.xhr(); 
      return myXhr; 
     }, 
     //Ajax events 
     success: function(output) { 
      document.write(output); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      alert(xhr.status); 
      alert(thrownError); 
     }, 
     // Form data 
     data: formData, 
     //Options to tell jQuery not to process data or worry about content-type. 
     cache: false, 
     contentType: false, 
     processData: false 
    }); 
}); 

與此問題:FORMDATA不包含類型爲「文件」的輸入欄位!

任何幫助表示讚賞:)

+0

所以,只需添加所需的輸入字段...? – Blazemonger

+0

問題到底是什麼?這怎麼不起作用? – David

+0

我在我的html中需要輸入字段。但由於某種原因,我的formData對象(var formData = new FormData($(「#editForm」)[0]);)不包括他們 – Stringering

回答

0

這個工作對我來說:

<input type="file" name="browseFile" id="photo" placeholder="File" /> 
<input id="userId" type="text" /> 

<input type="submit" value="create request" onclick="CreateRequest(event)" 


<script> 
     function CreateRequest(event) { 
      event.preventDefault ? event.preventDefault() : event.returnValue = false; 

      var inputFilePhoto = document.getElementById("photo"); 
      var imageFile = inputFilePhoto.files[0]; 

      var userId = document.getElementById("userId").value; 


      var formData = new FormData();    
      formData.append("RequestPhoto", imageFile); 
      formData.append("UserId", userId); 

      $.ajax({ 
       type: "POST", 
       url: "/User/CreateRequest", 
       data: formData, 
       contentType: false, 
       processData: false, 

       success: function() { 
        alert("OK"); 
       }, 
       error: function() { 
        alert("Error"); 
       } 

      }); 
+0

謝謝,但這對我不起作用。出於某種原因,imageFile沒有正確地附加到formData。當附加文本輸入字段時,它工作正常。 – Stringering