我想將傳入的照片保存到檔案夾中。我想將名稱保存為Guids,以便在進入同名檔案時沒有問題,但是我的代碼中似乎有錯誤。我沒有使用 guid,我不知道如何使用它。
public async Task<ApiResponse<SliderResponse>> Handle(SliderCreate request, CancellationToken cancellationToken)
{
byte[] bytes = null;
using (BinaryReader br = new BinaryReader(request.file.OpenReadStream()))
{
bytes = br.ReadBytes((int)request.file.OpenReadStream().Length);
}
Guid ImageFileName = new Guid ((request.file.FileName).ToString());
var FileContentType = request.file.ContentType;
var ImageContent = bytes;
using (var ms = new MemoryStream(bytes))
{
var path = Environment.CurrentDirectory @"\File";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (var fs = new FileStream(path @"\" ImageFileName , FileMode.Create ))
{
ms.WriteTo(fs);
}
}
var mapped = _mapper.Map<Slider>(request);
if (mapped == null)
return new ErrorApiResponse<SliderResponse>(ResultMessage.NotCreatedSlider);
var model = await _repo.Sliders.AddAsync(mapped);
var response = _mapper.Map<SliderResponse>(model);
return new SuccessApiResponse<SliderResponse>(response);
}
uj5u.com熱心網友回復:
消除
Guid ImageFileName = new Guid ((request.file.FileName).ToString());
(因為您傳遞給 Guid 建構式的字串應該是代表 Guid 的字串 - 它類似于 Guid.Parse。不要傳遞不代表 Guid 的字串,例如“IMG_0123.JPG”您的用戶上傳 - 此影像檔案名不代表 guid)
改變
using (var fs = new FileStream(path @"\" ImageFileName , FileMode.Create ))
到
using (var fs = new FileStream(Path.Combine(path, Guid.NewGuid().ToString()) , FileMode.Create ))
使用 Path.Combine 組合路徑。它了解運行它的系統的不同目錄分隔符。如果你硬編碼一個 windows 反斜杠,然后在 Linux 上運行你的應用程式,你會得到一個驚喜.. Path.Combine 接受 N 個引數并將它們構建成一個路徑。查看 Path 中可用的其他方法 - 那里有一些方便的東西
如果您希望檔案具有擴展名,可以將其從請求檔案名中拉出Path.GetExtension(request.file.FileName),并將其添加到 Guid 字串中,例如Path.Combine(path, $"{Guid.NewGuid()}{Path.GetExtension(request.file.FileName)}")
在呼叫 CreateDirectory 之前,您也不需要檢查目錄是否存在 - 在存在的目錄上呼叫 CreateDirectory 是非操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310984.html
