0
我在不同的網站發現了這個代碼或類似的代碼,在我的應用程序中,沒有引發錯誤,但下載了PDF文件,打開文件時已損壞,其只有5KB下載pdf文件與.NET Core損壞
文件的網址是:
「https://optionline-api-files.s3.amazonaws.com/pla592d774e504e8.pdf」
我用它來下載的代碼是:
[HttpPost]
[Route("api/[controller]/UploadFileToAzureStorage")]
public async Task<IActionResult> GetFile([FromBody]PDF urlPdf)
{
string localFilePath = await CreateTemporaryFile(urlPdf.urlPDF);
// Create storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccount);
// Create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Get a reference to a container named "mycontainer."
CloudBlobContainer container = blobClient.GetContainerReference(UploaderStorage.Container);
// Get a reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with the contents of a local file
// named "myfile".
using (var fileStream = System.IO.File.OpenRead(localFilePath))
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
return Ok();
}
/// <summary>
/// Creates temporary file
/// </summary>
/// <param name="urlPdf">PDF URL</param>
/// <returns>Returns path of the new file</returns>
private async Task<string> CreateTemporaryFile(string urlPdf)
{
Uri uri = new Uri(urlPdf);
string filename = default(string);
filename = System.IO.Path.GetFileName(uri.LocalPath);
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(urlPdf, HttpCompletionOption.ResponseHeadersRead))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
string fileToWriteTo = @"\\pc030\TemporaryPDF\"+filename;
using (Stream streamToWriteTo = System.IO.File.Open(fileToWriteTo, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
}
return await Task.FromResult(@"\\pc030\TemporaryPDF\" + filename);
}
你能嘗試沒有指定'HttpCompletionOption.ResponseHeadersRead'?對我來說,它只會下載標題並忽略響應主體。 – juunas
等待Task.FromResult(不管)什麼都可以替換。它已經過時了 –