【发布时间】:2019-03-11 22:00:13
【问题描述】:
我正在尝试将所选文件保存到本地文件夹。 这是我的一些代码:
<!-- HTML -->
<input id="menu-upload" name="pdf" type="file" accept="application/pdf">
.
// JS
document.getElementById('menu-upload').addEventListener("change", (event) => {
let file = event.target.files[0];
fetch("https://pdf/upload", {
method: "post",
headers: {
"Content-Type": file.type
},
body: file
}).then((resp) => {
console.log(resp);
});
}
.
// C# .NET 4.7.2
// CefSharp.WinForms v67.0.0
cef_settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "https",
DomainName = "pdf",
SchemeHandlerFactory = new PdfSchemeHandlerFactory(),
IsCorsEnabled = true
});
class PdfSchemeHandlerFactory : ISchemeHandlerFactory
{
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
/* This is where I'm having problems.
Whenever I inspect `request`,
it's `Method` is "OPTIONS"
and PostData is null.
See linked image. */
return ResourceHandler.ForErrorMessage("Test", System.Net.HttpStatusCode.OK);
}
}
由于我没有足够的代表来发布图片,here's the link
有没有更好的方法将文件数据从 JS 传递到 C#?
【问题讨论】:
-
您需要对发送请求的服务器启用 CORS。在尝试从您的代码中进行 POST 之前,您的浏览器正在发送 CORS 预检 OPTIONS 请求。显然预检失败了。所以浏览器就停在那里,从不尝试 POST。要使其正常工作,您需要使服务器使用 200 OK 和正确的 CORS Access-Control-Allow-* 标头响应 OPTIONS 请求。并且您需要使其还发送回正确的 CORS Access-Control-Allow-* 标头以响应 POST。
-
最简单的选择可能是将您的方案处理程序注册到您的主域的子域。基本上一起避免 cors 请求。
-
谢谢大家。我会试试你的建议。
-
其实可以添加白名单条目,见cefsharp.github.io/api/67.0.0/html/…
-
我添加了这个,但我仍然收到“OPTIONS”请求,JS 文件在 viewer.pdf.local 中:
Cef.AddCrossOriginWhitelistEntry( sourceOrigin: "https://upload.pdf.local", targetProtocol: "https", targetDomain: "pdf.local", allowTargetSubdomains: true );
标签: c# post fetch-api cefsharp