1

我编写了文件上传代码,可以很好地上传文件并将其保存在文件夹中。我已经包含一个功能,允许用户加载 PDF 文件的 URL,并且应该上传和保存来自 URL 的文件。编码:

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

如果我将上面的代码用于 load_URL,则会出现错误:TypeError: file.files is undefined fd.append('file', file.files[0]);

4

2 回答 2

1

不要使用 Files API(可用于从文件输入读取本地文件)。只需将 URL 发送到服务器并让您的服务器端代码获取它。

于 2013-03-26T13:46:38.230 回答
0

使用WebClient类从远程 url 下载文件。您可以使用该DownloadFile方法从远程 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();
}

如果要将文件保存在项目的App_Data文件夹中,可以像这样更改 targetPath 变量值

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

您可以解析 fileUrl 并从中获取文件名并为其添加唯一标识符(以避免覆盖具有相同名称的不同文件)并使用它来保存文件。

于 2013-03-26T13:52:42.787 回答