我正在通過一個表單上傳多個檔案,然后遍歷每個檔案并創建一個零位元組臨時檔案并使用GetTempFileName獲取檔案名。有沒有辦法復制檔案本身而不僅僅是檔案名和零位元組?代碼運行,但我總是在我的 API 的另一端得到零位元組檔案,這應該發生。我的代碼如下所示。
public async Task<IActionResult> UploadDocumentsAsync(Documents files)
{
try
{
List<string> tempFilePath = new List<string>();
List<string> fileName = new List<string>();
foreach (var doc in files.documents)
{
tempFilePath.Add(Path.GetTempFileName());
fileName.Add(doc.FileName);
}
MultipartFormDataContent formData = new MultipartFormDataContent();
var filePath = tempFilePath;
string token = Token();
List<FileStream> streams = new List<FileStream>();
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
for (int i = 0; i < tempFilePath.Count; i )
{
var fileStream = new FileStream(tempFilePath[i], FileMode.Open);
formData.Add(new StreamContent(fileStream), fileName[i], fileName[i]);
streams.Add(fileStream);
}
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(_configuration["Application:AppDomain"]) "api/Document")
{
Content = formData
};
request.Headers.Add("accept", "application/json");
var response = await client.SendAsync(request);
streams.ForEach(stream =>
{
stream.Dispose();
});
if (response.IsSuccessStatusCode)
{
//Handle success
}
//Handle failure
}
}
}
catch (Exception e)
{
//Handle the exception
}
}
uj5u.com熱心網友回復:
如果您想稍后訪問它,您需要將實際檔案保存到臨時檔案名
public async Task<IActionResult> UploadDocumentsAsync(Documents files)
{
try
{
List<string> tempFilePath = new List<string>();
List<string> fileName = new List<string>();
foreach (var doc in files.documents)
{
string fileTempFileName = Path.GetTempFileName();
tempFilePath.Add(fileTempFileName );
fileName.Add(doc.FileName);
using(Stream outStream = File.OpenWrite(Path.Combine(Path.GetTempPath(), fileTempFilePath )))
{
doc.CopyTo(outStream);
}
}
//Continue your code [...]
}
catch (Exception e)
{
//Handle the exception
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/454519.html
