C# 下载的pdf文件与.NET Core一起损坏
我在不同的网站上发现了这段代码或类似的代码,在我的应用程序中,没有抛出错误,但下载的PDF文件在打开时已损坏,并且只有5KB 文件的url为: 我用来下载的代码是:C# 下载的pdf文件与.NET Core一起损坏,c#,.net,asp.net-core,asp.net-core-mvc,.net-core,C#,.net,Asp.net Core,Asp.net Core Mvc,.net Core,我在不同的网站上发现了这段代码或类似的代码,在我的应用程序中,没有抛出错误,但下载的PDF文件在打开时已损坏,并且只有5KB 文件的url为: 我用来下载的代码是: [HttpPost] [Route("api/[controller]/UploadFileToAzureStorage")] public async Task<IActionResult> GetFile([FromBody]PDF urlPdf) {
[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);
}
您应该考虑一种解耦设计,它将使您的应用程序更易于维护和测试
interface IStreamLoader
{
Task<Stream> GetStreamAsync( Uri uri );
}
interface IStreamRepository
{
Task<Stream> GetAsync( string id );
Task PutAsync( string id, Stream stream );
Task DeleteAsync( string id );
}
public class MyController
{
private readonly IStreamLoader _streamLoader;
private readonly IStreamRepository _streamRepository;
public MyController( IStreamLoader streamLoader, IStreamRepository streamRepository )
{
_streamLoader = streamLoader;
_streamRepository = streamRepository;
}
[Route("api/[controller]/UploadFileToAzureStorage")]
public async Task<IActionResult> GetFile([FromBody]PDF urlPdf)
{
Uri pdfUri = new Uri( urlPDF.urlPDF );
using ( var pdfStream = await _streamLoader.GetStreamAsync( pdfUri ) )
{
await _streamRepository.PutAsync( "myblob", pdfStream );
}
return Ok();
}
}
最后,我们需要Azure的IStreamRepository实现:
class AzureStreamRepository : IStreamRepository
{
private readonly CloudStorageAccount _storageAccount;
private readonly string _containerName;
public AzureStreamRepository( string connectionString, string containerName )
{
_storageAccount = CloudStorageAccount.Parse( connectionString );
_containerName = containerName;
}
public async Task DeleteAsync( string id )
{
var blockBlob = GetBlockBlob( id );
await blockBlob.DeleteAsync();
}
public async Task<Stream> GetAsync( string id )
{
var blockBlob = GetBlockBlob( id );
Stream result = new MemoryStream();
try
{
await blockBlob.DownloadToStreamAsync( result );
}
catch ( Exception )
{
result.Dispose();
throw;
}
result.Seek( 0, SeekOrigin.Begin );
return result;
}
public async Task PutAsync( string id, Stream stream )
{
var blockBlob = GetBlockBlob( id );
await blockBlob.UploadFromStreamAsync( stream );
}
private Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob GetBlockBlob( string id )
{
var client = _storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference( _containerName );
return container.GetBlockBlobReference( id );
}
}
您可以在不指定HttpCompletionOption.ResponseHeadersRead的情况下尝试吗?对我来说,这看起来只会下载标题,而忽略响应body.wait Task.FromResult which可以替换为which。它已经过时了
class AzureStreamRepository : IStreamRepository
{
private readonly CloudStorageAccount _storageAccount;
private readonly string _containerName;
public AzureStreamRepository( string connectionString, string containerName )
{
_storageAccount = CloudStorageAccount.Parse( connectionString );
_containerName = containerName;
}
public async Task DeleteAsync( string id )
{
var blockBlob = GetBlockBlob( id );
await blockBlob.DeleteAsync();
}
public async Task<Stream> GetAsync( string id )
{
var blockBlob = GetBlockBlob( id );
Stream result = new MemoryStream();
try
{
await blockBlob.DownloadToStreamAsync( result );
}
catch ( Exception )
{
result.Dispose();
throw;
}
result.Seek( 0, SeekOrigin.Begin );
return result;
}
public async Task PutAsync( string id, Stream stream )
{
var blockBlob = GetBlockBlob( id );
await blockBlob.UploadFromStreamAsync( stream );
}
private Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob GetBlockBlob( string id )
{
var client = _storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference( _containerName );
return container.GetBlockBlobReference( id );
}
}
public class MyController
{
public MyController() : this(
new StreamLoader( @"\\pc030\TemporaryPDF\" ),
new AzureStreamRepository( StorageAccount, UploaderStorage.Container ) )
{}
}