简体   繁体   中英

Uncaught type error while uploading the file jquery

Hello i am using a from to upload the song on my wordpress website.I use a form where a person can upload one/multiple song files to the server.

My form is :

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

I want to get the file name after selecting file using the form(before pressing the submit).

I used this code:

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

AND

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

But there is a console error : Uncaught TypeError: Cannot read property 'name' of undefined

How i can solve this??

And how i can get the full URL using the file ??

For example : one url is : http://website.com/wp-content/uploads/2015/12/mpthreetest.mp3

Another usrl is : http://website.com/wp-content/uploads/2013/09/mpthreetest.mp3

So i need only the date to be fixed on url and i will get file name from the code

Uncaught TypeError: Cannot read property 'name' of undefined

It's probably referring to jQuery('#songs').prop("files")[0]['name'] .

The following is an empty jQuery object:

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

To answer your question "How i can solve this" , start by looking at why your selector jQuery('#songs').prop("files") isn't matching anything.

EDIT

Inspect the element with ID songs , can you see a files property? Is it an array? Does it contain anything? Does the first element contain a name property?

Your error could also come from the alert line: alert(song_file.name);

Just check the console, it'll point you to the right line.

It looks like you are looking at it on pageload, when it's still empty. You should look at the files on any change events to the input field, like this:

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);
    }
  });
})

Working jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM