我正在尝试将所选文件保存到本地文件夹。 这是我的一些代码:
<!-- 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#?
答案 0 :(得分:0)
这是我根据问题中的评论来解决此问题的方法:
我没有将file
作为请求的body
直接提供,而是将其放置在FormData
内。
// JS
var form = new FormData();
form.append("pdf", file);
fetch("https://upload.pdf.local/" + cur_folder, {
//fetch("http://localhost/api/" + cur_folder, {
method: "post",
//mode: "cors",
headers: {
"Content-Type": "multipart/form-data"
},
body: form
});
现在,OPTIONS
请求消失了,但是POST
请求仍然失败,而没有将标头Access-Control-Allow-Origin
设置为request.ReferrerUrl
。
// C# .NET 4.7.2
// CefSharp.WinForms v67.0.0
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
// .......
Directory.CreateDirectory(folder);
var filename = DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm") + ".pdf";
folder = Path.Combine(folder, filename);
File.Copy(data.File, folder, false);
var rh = (ResourceHandler)ResourceHandler.ForErrorMessage("Yay!", System.Net.HttpStatusCode.OK);
rh.Headers["Access-Control-Allow-Origin"] = "https://viewer.pdf.local";
return rh;
// .......
}