簡體   English   中英

上載文件jquery時出現未捕獲的類型錯誤

[英]Uncaught type error while uploading the file jquery

您好,我正在使用from來將歌曲上傳到我的wordpress網站上。我使用一種表格,一個人可以將一個/多個歌曲文件上傳到服務器。

我的表格是:

<form enctype="multipart/form-data" action="" method="post">
  <input type="file" name="songs[]" id="songs" multiple="multiple">
  <input type="submit" value="submit">
</form>

我想在使用表單選擇文件后獲得文件名(按提交之前)。

我使用以下代碼:

var song_file = jQuery('#songs')[0].files[0]
  if(song_file){
  alert(song_file.name);
}

var filename = jQuery('#songs').prop("files")[0]['name'];
alert(filename);

但是存在控制台錯誤: Uncaught TypeError: Cannot read property 'name' of undefined

我該如何解決?

以及如何使用文件獲取完整的URL?

例如:一個網址是: http://website.com/wp-content/uploads/2015/12/mpthreetest.mp3 : http://website.com/wp-content/uploads/2015/12/mpthreetest.mp3

另一個http://website.com/wp-content/uploads/2013/09/mpthreetest.mp3是: http://website.com/wp-content/uploads/2013/09/mpthreetest.mp3 ://website.com/wp-content/uploads/2013/09/mpthreetest.mp3

所以我只需要將日期固定在url上,我將從代碼中獲取文件名

未捕獲的TypeError:無法讀取未定義的屬性“名稱”

它可能是指jQuery('#songs').prop("files")[0]['name']

以下是一個空的jQuery對象:

jQuery('#songs').prop("files")

要回答您的問題“我如何解決此問題” ,請首先查看為什么選擇器jQuery('#songs').prop("files")不匹配任何內容。

編輯

檢查帶有ID songs的元素,可以看到files屬性嗎? 是數組嗎? 是否包含任何內容? 第一個元素是否包含name屬性?

您的錯誤也可能來自alert行: alert(song_file.name);

只需檢查控制台,它將指向您正確的行。

看起來您在頁面加載中仍在空白時正在查看它。 您應該在輸入字段的任何更改事件上查看文件,如下所示:

jQuery的

jQuery(document).ready(function() {
  jQuery("input:file").change(function(event) {
    var song_file = $('#songs')[0].files[0];
    if (song_file) {
      alert(song_file.name);
    }
  });
})

工作jsFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM