user2031327
user2031327

Reputation:

How to upload file where filepath is URL

I have written file upload code that work fine for uploading a file and saving it in a folder. I have included a functionality that allows the user to load URL of the PDF file and than the file from URL should be uploaded and saved. The code:

function loadURL(box) {
       var box = dhtmlx.modalbox({
           title: "Load URL",
           text: "<div id='form_in_box'><div>Enter the URL of PDF file <hr/><div><div><textarea id='file' style='width: 400px; height: 27px;'></textarea></div><span class='dhtmlx_button'><input type='submit' value='Load URL' style='width: 86px' onclick='save_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
           width: "300px"
       })
   }

function save_file(box) {
       var file = document.getElementById('file');
       if (file.value == "") {
           alert("Choose a file to upload");
           return false;
       }
       dhtmlx.modalbox.hide(box);

       var fd = new FormData();
       fd.append('file', file.files[0]);
       var xhr = new XMLHttpRequest();
       xhr.open('POST', '/FileUpload/Upload', true);
       xhr.onreadystatechange = function () {
           if (xhr.readyState == 4 && xhr.status == 200) {
               alert('File successfully uploaded to the server');
           }
       };
       xhr.send(fd);

} If i use the above code for load_URL am getting error as: TypeError: file.files is undefined fd.append('file', file.files[0]);

Upvotes: 1

Views: 1463

Answers (2)

Shyju
Shyju

Reputation: 218722

Use WebClient class to download the file from the remote url. You can use the DownloadFile method to download a file from a remote url.

public ActionResult DownloadFile(string fileName)
{
    if (!String.IsNullOrEmpty(fileName))
    {
        using (WebClient wc = new WebClient())
        {      
            string targetPath = @"C:\YourFolder\thatUniqueFileName.pdf";         
            wc.DownloadFile(fileName,targetPath);

            return RedirectToAction("Downloaded"); //PRG pattern
        }
    }
    return VieW();
}

If you want to save the files in your App_Data folder of the project, you can change the targetPath variables value like this

string targetPath = HttpContext.Server.MapPath("~/App_Data/yourPdf.pdf");

You could parse the fileUrl and get the file name from that and add a unique identifier to that(to avoid overwriting of different files with same name) and use that to save the files.

Upvotes: 0

Quentin
Quentin

Reputation: 943207

Don't use the Files API (which you can use for reading a local file from a file input). Just send the URL to the server and have your server side code fetch it.

Upvotes: 1

Related Questions