我有一个适用于 Chrome 的文件上传代码,但对于 IE 会抛出以下错误。
"IOException: The process cannot access the file 'path\filename' because it is being used by another process. System.IO.__Error.WinIOError(int errorCode, string maybeFullPath) System.IO.FileStream.Init(string path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, string msgPath, bool bFromProxy, bool useLongPath, bool checkHost) System.IO.FileStream..ctor(string path, FileMode mode, FileAccess access, FileShare share) System.IO.File.OpenWrite(string path) RES.Controllers.DataHandling.DataUploadController+d__5.MoveNext() in DataUploadController.cs +
Controller 操作方法如下:
public async Task<IActionResult> Upload(UploadedData data)
{
var filename=string.Empty;
if (ModelState.IsValid)
{
var file = data.File;
var parsedContentDisposition =
ContentDispositionHeaderValue.Parse(file.ContentDisposition);
filename = Path.Combine(_hostingEnvironment.ContentRootPath,
"UplaodedFiles", parsedContentDisposition.FileName.Trim('"'));
using (var stream = System.IO.File.OpenWrite(filename))
{
await file.CopyToAsync(stream);
}
}
}
查看下面的模型:
public class UploadedData
{
public IFormFile File { get; set; }
}
我可以想象代码没有任何问题,因为它适用于 Chrome。有谁知道 IE 的问题是什么吗?
最佳答案
这是由于 Internet Explorer 和 Chrome 之间的行为不同造成的。
出于安全原因,Chrome 隐藏了用户目录的路径。
这意味着您只能获取变量中的文件名(例如 myfile.txt
)。
而 Internet Explorer 会为您提供上传文件的完整客户端路径 (C:\Users\User1\myfile.txt
)。
Path.Combine
然后失败并返回客户端路径(例如 C:\Users\User1\myfile.txt
),而不是上传目录的组合路径。
您的服务器无法打开该文件,因为在您的测试/开发环境中该文件是由您的浏览器打开的。
filename = Path.Combine(@"D:\",
"UploadedFiles", Path.GetFileName(parsedContentDisposition.FileName.Trim('"')));
在 parsedContentDisposition.FileName
周围使用 Path.GetFileName(..)
可以解决该问题。
简而言之:
IE 中的Path.Combine
尝试合并 D:\
、UploadedFiles
和 C:\Users\User1\myfile。 txt
导致 C:\Users\User1\myfile.txt
并失败。
Path.Combine
尝试合并 D:\
、UploadedFiles
和 myfile.txt
,结果在 D:\UploadedFiles\myfile.txt
中并成功。
我认为这种行为是由于 Chrome 和 Firefox 中的这种安全机制造成的,在 this question on Stack Overflow 上进行了讨论。 .
编辑: Internet Explorer 仅上传本地 Intranet 区域内标准设置的完整路径。
关于c# - ASP.NET CORE 文件上传问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44718080/