ASP.NET文件上传并在同一页面上显示.NET Core 2.1



我是asp.net的新手,我只需要显示一个file upload控件(用于上传pdf(,当用户选择一个文件时,同一页面会在文件上传控件的正下方显示pdf。我从自己设置基础知识中学到了很多东西。但由于某种原因,我无法将上传的pdf显示在我在页面上设置的object元素中。我确信我在代码中做了很多其他错误的事情,所以请建议改进。请参阅以下内容。

请原谅这个代码中的天真:

Razor cshtml文件:

@using (Html.BeginForm("PickPdf", "EditPdf", FormMethod.Post, new { id = "fileUploadControl", enctype = "multipart/form-data" }))
{
<input type="file" name="file" class="chooseFileButton" />
<input type="submit"
name="Upload"
id="Submit"
value="View PDF"
class="chooseFileButton"
onclick="Validation" />
<br><br>
<p>@ViewBag.Message</p>
<object id="pdfObject" name="pdfObject" data=@ViewData["FormFile"] type="application/pdf" width="400" height="200"></object>
}

C#控制器:

public IActionResult Index()
{
return this.CustomView("");
}    
[HttpPost]
public ActionResult PickPdf(){
var files = Request.Form.Files;
if(files != null && files.Count > 0)
{
IFormFile selectedFile = files[0];
return this.CustomView(selectedFile.FileName, selectedFile);
}
return this.CustomView("File could not be processed");
}

private ActionResult CustomView(string message, IFormFile formFile = null){
var returnView = View("Index");
returnView.ViewData["Message"] = message;
if(formFile != null){
var readStream = formFile.OpenReadStream();
byte[] bytes = new byte[readStream.Length];
readStream.Read(bytes, 0, Convert.ToInt32(readStream.Length));
returnView.ViewData["FormFile"] = bytes;
}
return returnView;
}

如果您希望在用户选择文件后立即显示PDF,则需要JavaScript。使用以下代码将事件处理程序绑定到文件输入的onchange事件:

$('#MyFileInput').on('change', function () {
var file = this.files[0];
if (file.type === 'application/pdf') {
var reader = new FileReader();
reader.onload = function(e) {
$('MyObjectTag').data = e.target.result;
}
reader.readAsDataURL(file);
}
});

这使用JavaScriptFileneneneba API读取用户选择的文件的内容,然后创建一个数据URL,然后可以将其分配给对象标记的data。检查mime类型很重要,这样别人就不能直接将任何内容加载到对象标记中。

此外,请注意,这实际上并没有"上传"任何内容。用户仍然需要实际提交表单(或者您需要通过AJAX发送表单数据(才能将实际文件发送到服务器。然而,这确实允许他们预览要上传的内容,而不会导致页面刷新或实际做任何不可逆转的事情(如果不是他们真正想要的文件,他们可以再次选择(。此外,由于文件API是必需的,因此它只能在现代浏览器(IE 10+和地球上几乎所有其他浏览器(中工作。

尝试这样修改方法。希望能帮忙,我的朋友:(

private ActionResult CustomView(string message, IFormFile formFile = null)
{
var returnView = View("Contact");
returnView.ViewData["Message"] = message;
if (formFile != null)
{
var readStream = formFile.OpenReadStream();
byte[] bytes = new byte[readStream.Length];                
readStream.Read(bytes, 0, Convert.ToInt32(readStream.Length));
var strBase64 = Convert.ToBase64String(bytes);
var content = string.Format("data:application/pdf;base64,{0}", strBase64);
ViewData["FormFile"] = content;
}
return returnView;
}

最新更新