我试图在上传后将每个文件的名称保存在数据库中。我有这个代码可以成功上传文件。
$(function () {
$("#uploader").plupload({
// General settings
runtimes: 'silverlight,flash,html5',
url: '@Url.Content( "~/FileUploadChunks/UploadChunk" )',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
// Flash settings
flash_swf_url: '/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: '/plupload/js/plupload.silverlight.xap'
});
});
这是控制器
[HttpPost]
public ActionResult UploadChunk(int? chunk, int chunks, string name)
{
var fileUpload = Request.Files[0];
var uploadpath = Server.MapPath("~/App_Data/UploadedFiles");
chunk = chunk ?? 0;
using (var fs = new FileStream(Path.Combine(uploadpath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
return Content("chunk uploaded", "text/plain");
}
为了测试,我尝试了类似的东西来尝试捕获名称并将它们添加到列表中以返回到视图,但我无法弄清楚如何在视图中打印出列表以查看其内容。 / p>
[HttpPost]
public ActionResult UploadChunk(int? chunk, int chunks, string name)
{
var fileUpload = Request.Files[0];
var uploadpath = Server.MapPath("~/App_Data/UploadedFiles");
chunk = chunk ?? 0;
using (var fs = new FileStream(Path.Combine(uploadpath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
List<string> list = new List<string>();
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file1 = Request.Files[inputTagName];
if (file1.ContentLength > 0)
{
list.Add(file1.FileName);
}
}
ViewBag.List = list;
}
最终我只是试图遍历名称并将它们保存在数据库中。任何帮助表示赞赏。感谢
答案 0 :(得分:0)
您没有提供有关您的数据库等的任何信息,以便我们为您提供良好的帮助。不过我会试一试。
要回答您的其他问题,
我尝试过这样的事情来尝试捕获名称并将其添加到 一个列表返回视图,但我无法弄清楚如何打印出来 视图中的列表可以查看其内容。
在您看来,这样的事情应该显示出来:
@foreach (string fileName in ViewBag.List)
{
@fileName
<br />
}
假设您使用Entity Framework Code Fist,要将文件名保存到数据库,您需要拥有一个模型。
public class UploadedFileName
{
public int Id { get; set; }
public string Name { get; set; }
}
然后在你的控制器中你可以改变你曾经使用过的foreach
语句:
foreach (HttpPostedFile file in Request.Files)
{
if (file.ContentLength > 0)
{
UploadedFileName uploadedFile = new UploadedFileName();
uploadedFile.Name = file.FileName;
databaseContext.UploadedFileNames.Add(uploadedFile);
}
}
如果您有错误,上面的HttpPostedFile
可能需要HttpPostedFileBase
。 databaseContext
是您的数据库上下文,通常是db
。