提问人:gkmnada 提问时间:9/10/2023 更新时间:9/10/2023 访问量:44
使用ajax从数据库下载文件(文件已损坏或无法打开)
Downloading file from database with ajax (File is corrupted or cannot be opened)
问:
我正在使用以下代码将文件保存到数据库中。
控制器.cs,
[HttpPost]
public IActionResult AddFile(IFormFile file, TaskListAttachment taskListAttachment)
{
if (file != null && file.Length > 0)
{
var fileName = Path.Combine("wwwroot/files", Path.GetFileName(file.FileName));
using (var stream = new FileStream(fileName, FileMode.Create))
{
file.CopyTo(stream);
}
taskListAttachment.FileName = file.FileName;
taskListAttachment.ContentType = file.ContentType;
taskListAttachment.Data = new byte[file.Length];
taskListAttachment.AddDateTime = DateTime.Now;
taskListAttachment.FilePath = fileName;
taskListAttachment.TaskId = Convert.ToInt32(Request.Form.Where(x => x.Key == "TaskId").FirstOrDefault().Value);
taskListAttachment.AddUserId = Convert.ToInt32(Request.Form.Where(x => x.Key == "AddUserId").FirstOrDefault().Value);
taskListAttachmentManager.itemAdd(taskListAttachment);
var addValue = JsonConvert.SerializeObject(taskListAttachment);
return Json(addValue);
}
else
{
return Json(null);
}
}
cshtml,
<script>
$("#fileInput").change(function () {
var fileName = $(this).val();
var fileExtension = fileName.split('.').pop().toLowerCase();
$("#fileExtension").val(fileExtension);
});
$("#uploadButton").click(function () {
var addUserId = $("#addUserId").data("user-id");
var taskId = $("#taskId").data("task-id");
var fileExtension = $("#fileExtension").val();
var formData = new FormData();
formData.append("AddUserId", addUserId);
formData.append("TaskId", taskId);
formData.append("FileExtension", fileExtension);
formData.append("file", $("#fileInput")[0].files[0]);
$.ajax({
url: "/TaskList/AddFile/",
type: "Post",
data: formData,
contentType: false,
processData: false,
success: function (result) {
var dismissModal = document.getElementById("dismissButton").click();
attachmentalert();
var FileInput = $('#fileInput');
FileInput.val('').focus();
}
});
});
</script>
然后,我编写了以下代码来下载保存的文件,
控制器.cs,
public IActionResult DownloadFile(int id)
{
var attachment = taskListAttachmentManager.itemGetById(id);
if (attachment != null)
{
return File(attachment.Data, attachment.ContentType, attachment.FileName);
}
else
{
return NotFound();
}
}
cshtml,
<a href="@Url.Action("DownloadFile", "TaskList", new {id = item.AttachmentID})" class="text-dark fs-4 link lh-sm">@item.FileName</a>
但是当我下载文件时,它们下载不正确或损坏。如果我下载 jpeg 或 png,图像将无法打开,如果我下载 rar 或 zip,我会收到存档已损坏或不正确的警告。办公文件和 pdf 也是如此。
问题是什么?
谢谢。
答: 暂无答案
上一个:控制器中的参数值为 null
评论
wwwroot/files