skip to Main Content

I have created a form that contains some inputs including one of type file and I want to check if when sending the form there are files selected or not and set the createObjectUrl to "" hat’s what I have but when I send the form it generates the error Uncaught TypeError: Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed.

submit.addEventListener('click', function(procesarImagen){
    procesarImagen.preventDefault();
    cont_rev_add.style.display = "none"
    rev_add.style.display = "initial"
    const archivo = input_file.files
    const PrimerArchivo = archivo[0]
    const objectURL = URL.createObjectURL(PrimerArchivo)
    if (!archivo || !archivo.length) {
        objectURL.URL.createObjectURL("")
    }
    review.push({
        name: input_name.value + "<br> <span id='title_t'>" + input_profession.value + "</span>",
        texto_review: input_review.value,
        img_review: objectURL
    }
    ) 
  })


I have tried modifying the if condition to check the length of the input and I hope to find the solution to this problem.

2

Answers


  1. Is this a typo?

    Here:

     objectURL.URL.createObjectURL("")
    

    Did you mean:

     objectURL = URL.createObjectURL("")
    

    This would be a better design:

    const archivo = input_file.files
    const PrimerArchivo = archivo[0]
    let objectURL = PrimerArchivo ? URL.createObjectURL(PrimerArchivo) : null;
    if (!objectURL) {
        objectURL = "";
    }
    
    Login or Signup to reply.
  2. In your code snippet, the error could be caused by the following line:

    ==> objectURL.URL.createObjectURL("")

    This line is attempting to create a new object URL, but the argument passed to createObjectURL() is an empty string. This is likely causing the error.

    To fix this issue, you can add a condition to check whether a file has been selected before creating the object URL. Here’s an updated version of the code that includes this check:

    submit.addEventListener('click', function(procesarImagen){
      procesarImagen.preventDefault();
      cont_rev_add.style.display = "none"
      rev_add.style.display = "initial"
      const archivo = input_file.files
      const PrimerArchivo = archivo[0]
      let objectURL = ''
      if (PrimerArchivo) {
        objectURL = URL.createObjectURL(PrimerArchivo)
      }
      review.push({
        name: input_name.value + "<br> <span id='title_t'>" + input_profession.value + "</span>",
        texto_review: input_review.value,
        img_review: objectURL
      })
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search