【发布时间】:2017-05-30 13:47:53
【问题描述】:
我在不同的网站找到了这个代码或类似的代码,在我的应用程序中,没有抛出错误,但是下载的 PDF 文件,打开时文件损坏,只有 5KB
文件的网址是:
“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试试吗?在我看来,它只会下载标题并忽略响应正文。 -
await Task.FromResult(whatever) 可以替换为任何内容。它已经过时了
标签: c# .net asp.net-core asp.net-core-mvc .net-core