2016-05-23 147 views
1

我已经将文件上载下面的方法:上传文件并将其保存在临时文件夹

[HttpPost] 
    public ActionResult Upload() 
    { 

     string directory = @"C:\Temp\"; 

     HttpPostedFileBase file = Request.Files["file"]; 

     if (file != null && file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 

      file.SaveAs(Path.Combine(directory, fileName)); 
     } 
     return RedirectToAction("Index"); 
    } 

,这里是我的Ajax调用:

$('#uploadButton').on('click', function() 
{ 

    $.ajax({ 
     type: "POST", 
     dataType: 'json', 
     url: '@Url.Action("Upload", "Application")', 
     timeout: 2000, 
     contentType: 'application/json', 
     success: function (data) { 

      //show content 
      alert('Success!') 
     } 
    }); 
} 
) 

我需要发送“ Request.files [“file”]“与上传的文件。

这里是我的代码所在的形式:

<form action="/profile/upload" method="post" enctype="multipart/form-data"> 

    <div class="form-group"> 

     <label>File</label> 

     <input type="file" name="file" id="file" class="form-control" /> 
     <br /> 
     <input type="button" id="uploadButton" value="Upload" /> 
    </div> 
</form> 
+0

什么语言你的服务器端代码写的?请为它添加标签。 – 2016-05-23 10:33:47

+0

您可以更改请求的contentType并尝试,我没有看到您是如何在代码中读取文件的。 – Nagaraj

回答

0

试试这个:

$('#uploadButton').on('click', function() { 
    var data = new FormData(); 
    var files = $('[type="file"]').get(0).files; 
    // Add the uploaded image content to the form data collection 
    if (files.length > 0) { 
     data.append("file", files[0]); 
    } 

    $.ajax({ 
     type: "POST", 
     url: '@Url.Action("Upload", "Application")', 
     type: 'POST', 
     data: data, 
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (data) { 
      //show content 
      alert('Success!') 
     } 
    }); 

}) 
+0

HttpPostedFileBase file = Request.Files [“file”];返回null –

+0

检查此Request.Files [0] –

相关问题