我正在嘗試從不同的輸入檔案框中上傳兩個檔案,而不使用 JQuery、AJAX 和 PHP 重繪 頁面。問題是檔案沒有上傳,可能是因為我形成的方式。附加這兩個檔案或我在 AJAX 中定義“資料”的方式。
這是我的 HTML 表單
<form>
<div class="col col-sm-12 mb-2">
<label class="form-label">Cover Image</label>
<input type="file" class="form-control" name="coverImage" id="coverImage">
</div>
<div class="col col-sm-12">
<label class="form-label">File to Embed</label>
<input type="file" class="form-control" name="fileToEmbed" id="fileToEmbed">
</div>
<button type="button" class="btn btn-primary" name="steganize" id="steganize">STEGANIZE</button>
</form>
這是我嘗試做的代碼。
$('#steganize').click(function(){
var file = $('#coverImage').prop("files")[0];
var form = new FormData();
form.append("coverImage", file);
var file2 = $('#fileToEmbed').prop("files")[0];
var form2 = new FormData();
form2.append("fileToEmbed", file2);
$.ajax({
url: "steganize.php",
type: "POST",
data: {form, form2},
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
});
});
也試過這個
$('#steganize').click(function(){
var file = $('#coverImage').prop("files")[0];
var file = $('#fileToEmbed').prop("files")[1];
var form = new FormData();
form.append("coverImage", file);
$.ajax({
url: "steganize.php",
type: "POST",
data: form,
contentType: false,
processData:false,
success: function(result){
console.log(result);
}
});
});
不幸的是,這兩個都不起作用。那么你知道正確的寫法嗎?我被困了幾個小時。如果您能幫助我,請提前致謝。
uj5u.com熱心網友回復:
您只能在 AJAX 請求中發送一個 FormData 物件,因此您的第二個示例接近正確。那里的問題是您重新定義file變數并且只附加其中一個值。
此外,由于使用,您在輸入中選擇了第二個檔案- 我假設您的意思是抓住第一個。fileToEmbed[1]
正確的代碼應如下所示:
$('#steganize').click(function() {
var coverImage = $('#coverImage').prop("files")[0];
var fileToEmbed = $('#fileToEmbed').prop("files")[0];
var form = new FormData();
form.append("coverImage", coverImage);
form.append("fileToEmbed", fileToEmbed);
$.ajax({
url: "steganize.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483390.html
