简体   繁体   中英

How to include enctype="multipart/form-data" if I am not using <form> tag to upload file to database?

I want to upload pdf file to my database. On skimming through various resources I found that we have to include attribute enctype="multipart/form-data" in form tag. Problem is am not using form to fill data (coz of CSS designing and framework). form data is submitted by onClick function.

So how can I still upload file? I think we cant include enctype attribute in tag?

You can simple do this by this jQuery function

function uploadFile(blobFile) {
    var fd = new FormData();
    fd.append("fileToUpload", blobFile);

    $.ajax({
       url: "upload.php",
       type: "POST",
       data: fd,
       processData: false,
       contentType: false,
       success: function(response) {
           // .. do something
       },
       error: function(jqXHR, textStatus, errorMessage) {
           console.log(errorMessage); // Optional
       }
    });
} 

Usage

For this input

<input type="file" id="filechooser">

Use this

uploadFile($('#filechooser')[0].files[0]);

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