文件上传保存空文件 [英] File-upload saves empty file
问题描述
我正在ASP.NET MVC 5上使用Ajax& jQuery在c#中编写文件上传模块
I am writing file uploading module in c# using ajax&jQuery on ASP.NET MVC 5
我尝试了msdn示例的后端代码
I tried msdn example for backend code
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count != 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Junk/"), fileName);
file.SaveAs(path);
}
}
return new EmptyResult();
}
问题是此方法创建了空文件(大小为0字节).我猜这是因为我们不读取输入流,而只读取示例中的文件名.
The problem is that this method creates empty file (size 0 bytes). I guess this happens because we don't read input stream, we're only reading filename on the example.
如何进行这项工作?
更新1(发布的js代码):
<script type="text/javascript">
$(document).ready(function () {
$("#Upload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
//beforeSend: beforeSendHandler,
success: function(){
alert("CAT");
},
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
ajaxRequest.done(function () {
alert("CAAT");
});
});
});
</script>
更新2(添加了html标记):
<div class="container body-content">
<hr />
<input type="file" id="FileUpload" multiple />
<input type="button" id="Upload" value="Upload" />
<hr />
<footer>
...
</footer>
</div>
推荐答案
您即将使用当前的代码.
You're nearly there with your current code.
I've read about this one on: https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/ and adapted my answer.
尝试一下:
// The same as you already have, but your button as a "button"
<div ...>
<input type="file" id="FileUpload" multiple />
<button type="button" id="Upload" value="Upload" />
...
</div>
您的jQuery:
<script type="text/javascript">
$(document).ready(function () {
$("#Upload").click(function () {
var files = $("FileUpload").target.files;
if (files.Length > 0)
{
// Check if the browser supports FormData
if (window.FormData !== undefined) {
var formData = new FormData();
// Add the files
for (var x = 0; x < files.length; x++){
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
url: 'Home/Upload?id=someId'
data: formData,
dataType: 'json',
contentType: false,
processData: false,
//beforeSend: beforeSendHandler,
success: function(){
alert("CAT");
},
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
ajaxRequest.done(function () {
alert("CAAT");
});
}
else {
// If the browser does not support FormData, show an alert
alert("Your browser does not support this type of upload");
}
});
}
});
</script>
您的控制器:
[HttpPost]
public ActionResult Upload(string id)
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and write the file to disk
var fileName = Path.GetFileName(file);
var path = Path.Combine(Server.MapPath("~/Junk"), fileName);
using (var fileStream = File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Upload failed");
}
return Json("Upload succeeded");
}
请注意,您可能需要更改几处内容,但这几乎是您所需要的.
Please note you might want to change a couple of things around, but this should be pretty much what you need.
希望这会有所帮助!
这篇关于文件上传保存空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!