【问题标题】:Uploading Document to App_Data将文档上传到 App_Data
【发布时间】:2015-09-13 04:17:08
【问题描述】:

我目前有一些工作代码可以将文档上传到 App_data 文件,但是如果上传的文件名称相同,我需要能够区分它们。我想通过像这样修改文件名来做到这一点:ID" "文件名

我曾多次尝试将它包含在传递给控制器​​的对象中,但我找不到它存储在任何地方(我认为它在传递时会被剥离?)。

这是我当前的代码:

var files = $('#txtUploadFile')[0].files;
if (files.length > 0) {
    if (window.FormData !== undefined) {
        var data = new FormData();
        for (var x = 0; x < files.length; x++) {
            data.append("file" + x, files[x]);
        }
        // data.uploadName = task.Id + " " + files[0].name; 

        // File.filename = Id + " " + file.filename;
        $.ajax({
            type: "POST",
            url: '../Document/UploadFiles/',
            contentType: false,
            processData: false,
            //data: {'id': (nextRef + 1), 'fileLocation': files[0].name }, // THIS DOESN'T WORK
            data: data, // THIS WORKS WITHOUT ANY OTHER VARIABLES
            dataType: "json",
            success: function (result) {
                //alert(result);
            },
            error: function (xhr, status, p3, p4) {
                var err = "Error " + " " + status + " " + p3 + " " + p4;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).Message;
                alert(log(err));
            }
        });
    } else {
        alert("This browser doesn't support HTML5 file uploads!");
    }
}



[HttpPost]
public JsonResult UploadFiles()//string id, string fileLocation)
{
    try
    {
        foreach (string file in Request.Files)
        {
            var hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
                continue;
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                var fileName = Path.GetFileName(file);
                var path = Path.Combine(Server.MapPath("~/App_Data/"), Path.GetFileName(hpf.FileName));

                // Save the file
                hpf.SaveAs(path); 
            }
        }
    }
    catch (Exception)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return this.Json("Upload failed");
    }

    return this.Json("File uploaded successfully");
}

【问题讨论】:

  • 您的代码似乎存在重大缺陷。当 userA 上传一个名为(比如说)Report.doc 的文件,而 userB 稍后上传一个也名为 Report.doc 的文件时会发生什么。为了解决这个问题和您当前发现的问题,您需要检查目录中是否存在同名的现有文件,如果存在,请给它一个新名称(例如附加后缀)

标签: c# html ajax asp.net-mvc file


【解决方案1】:

url: '../Document/UploadFiles/', 更改为url: '@Url.Action("UploadFiles","YourController") 在你的控制器中

public class YourController:Controller{
  [HttpPost]
   publiction ActionResult UploadFiles(){
        if (Request.Files != null && Request.Files.Count > 0)
        {              
          string path=Server.MapPath("~/App_Data");
          Request.Files[0].SaveAs(path + fileName);
      return Json("File uploaded","text/json",JsonRequestBehavior.AllowGet);
        }
      return Json("No File","text/json",JsonRequestBehavior.AllowGet);
   }
}

【讨论】:

    【解决方案2】:

    你的 html 应该是

    <div><input type="file" name="UploadFile" id="fileupload" Class="fileupload"  />
    </div> 
    

    你的ajax调用应该是

     $.ajax({
               type: "POST",
               url: '/MyController/UploadFiles?id=' + myID,
               contentType: false,
               processData: false,
               data: data,
               success: function(result) {
                   console.log(result);
               },
               error: function (xhr, status, p3, p4){
    
                });
    

    //和你的控制器

     [HttpPost]
     public JsonResult UploadFiles(string id)  
     {
                // whatever you want to that id
     }
    

    编码愉快...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      相关资源
      最近更新 更多