在我的MVC应用程序中,允许用户上传PDF文件并将上传的文件保存在文件夹中。文件正在上传,但它没有保存在文件夹中...... 查看代码是:
<a class="upload" onclick="upload(this);">
function upload(box) {
var box = dhtmlx.modalbox({
title: "Upload File",
text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' 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 filename = $("#filename").val();
if (filename == "") {
alert("Enter the URL");
return false;
}
dhtmlx.modalbox.hide(box);
dhtmlx.message("Uploading the file");
$.post("/FileUpload/UploadURL",
{ filename: '' + filename + '' });
}
控制器代码是:
public ActionResult UploadURL(FormCollection data)
{
var filename=data["filename"];
SaveNewFile(filename);
return View();
}
public ActionResult SaveNewFile(string file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file) ?? "";
if (file.Length > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_fileUploadPath),
Path.GetFileName(file));
if (!System.IO.File.Exists(filePath))
{
filePath = Server.MapPath(_fileUploadPath + file);
TempData["UploadValidationMessage_Success"] = "File upload Succeeded.";
return View();
}
else
{
TempData["UploadValidationMessage_Failure"] = "File already exist.";
return View();
}
}
else
{
TempData["UploadValidationMessage_Failure"] = "Only PDF files are supported. Try again...";
return View();
}
}
答案 0 :(得分:1)
你没有保存它。请参阅以下帖子了解如何保存文件:
有关完整教程:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
答案 1 :(得分:0)
使用HttpPostedFileBase uploadFile
参数接受上传文件,SaveAs(filePath);
保存!
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
同时将您的JQuery Post更改为Jquery Ajax帖子
$('form').submit(function(event) {
event.preventDefault();
var file = $("#filename").val();
file = file.serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: "/FileUpload/UploadURL",
data: file,
success: function( data )
{
alert( data );
}
});
return false;
}
</script>
答案 2 :(得分:0)
答案 3 :(得分:0)
首先,您需要告诉EncType表单。没有encType文件将不会发布到服务器
<form action="" method="post" enctype="multipart/form-data">
</form>
用于剃刀
@using (Html.BeginForm("Index", "yourCOntroller", FormMethod.POST, new { enctype = "multipart/form-data" }))
{
// some stuff
}