c# - 使用jquery mvc 4上传pdf文件
问题描述
我正在尝试使用 jquery 上传文件,它适用于文本文件,但是当我尝试上传 pdf 文件时,它会出错并且总是将 0 返回到 Request.Files.Count。
实际上,我正在尝试在上传之前预览文档,所以首先我在预览文件夹中上传了一个文档,然后我使用 pdf 查看器将其显示在 div 中,如果他选择另一个文档,我将删除最后一个文档并上传新文档,但我的问题是我的代码只适用于 .txt 文件,我想要 pdf
我尝试了 2 小时,但不明白错误请帮忙!
客户端代码
HTML
<input id="file" class="form-control-file" type="file" name="file" placeholder="Document Upload" />
jQuery
$("#file").change(function () {
var formData = new FormData();
var totalFiles = document.getElementById("file").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file").files[i];
formData.append("file", file);
}
$.ajax({
type: "POST",
url: '/Admin/PreviewUpload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
});
服务器端代码
[HttpPost]
public ActionResult PreviewUpload()
{
if (Request.Files.Count > 0)
{
foreach (string files in Request.Files)
{
var _file = Request.Files[files];
FileInfo Fi = new FileInfo(Path.GetFileName(_file.FileName));
string fileExtention = Fi.Extension;
if (_file != null)
{
if (fileExtention == ".PDF")
{
string fileName = Path.GetFileName(_file.FileName);
if (_file.ContentLength <= 120000000)
{
_file.SaveAs(Server.MapPath("~/PreviewPDF/" + fileName));
}
string path = "/PreviewPDF/" + Path.GetFileName(_file.FileName);
ViewData["error"] = path;
return Json(new
{
Success = path
});
}
else
{
return Json(new
{
fileError = "Only Support PDF"
});
}
}
else
{
return Json(new
{
error = "Please Select the file"
});
}
}
}
return Json(new
{
error = "Please Select the file"
});
}
解决方案
如果要上传大文件,则需要更改配置。
更多详情点这里点我
如果“Web.config”文件中尚未添加,则需要添加/更新“executionTimeout”、“maxRequestLength”和“maxAllowedContentLength”属性的值,如下所示。
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" /> // here your project version
<!-- executionTimeout = 30hrs (the value is in seconds) and maxRequestLength = 1GB (the value is in Bytes) -->
<httpRuntime targetFramework="4.5.2" executionTimeout="108000" maxRequestLength="1073741824" />
</system.web>
<system.webServer>
<!-- maxAllowedContentLength = 1GB (the value is in Bytes) -->
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
推荐阅读
- elasticsearch - 带有 filebeat 的 K8s Elasticsearch 在重新启动后保持“未准备好”
- html - 如何在html中将文本框和按钮保持在同一行
- bitbucket-api - Bitbucket api 为提交拉取请求返回 400
- css - 像 Firefox 一样的 CSS Scroll Snap 行为
- python - 为每个键构建一个字典,包含一组来自元组列表的关联值
- react-native - React Native 'popover' 组件与导航
- flutter - 方法“[]”在 null 上调用,但在 App 中有效
- angular-cli - ng 使用 Angular 服务时出现“地址不可用”错误
- python - TypeError:无法腌制弱引用对象
- python-3.x - python中的main.py到底是什么,我如何使用它来使用pyinstaller创建一个可执行文件?