我在我的网站上添加了一个下载图片的链接。当我点击链接时,希望自动开始下载。
目前,当我点击链接时,我收到的响应消息是:例如:
StatusCode: 200,ReasonPhrase: 'OK',Version: 1.1,Content: System.Net.Http.PushStreamContent,Headers:{Content-Type:application/octet-stream Content-Disposition:attachment;filename=895621d7-57a4-47a5-8dc5-ae36a2623826Banneraaaaaaaa.jpg}
我该如何修改以下代码以自动开始下载?我认为我可能返回了错误的类型:
以下是我的代码:
目前,当我点击链接时,我收到的响应消息是:例如:
StatusCode: 200,ReasonPhrase: 'OK',Version: 1.1,Content: System.Net.Http.PushStreamContent,Headers:{Content-Type:application/octet-stream Content-Disposition:attachment;filename=895621d7-57a4-47a5-8dc5-ae36a2623826Banneraaaaaaaa.jpg}
我该如何修改以下代码以自动开始下载?我认为我可能返回了错误的类型:
以下是我的代码:
public HttpResponseMessage DownloadImageFile(string filepath)
{
filepath = "https://mysite.com/" + filepath;
try
{
var response = new HttpResponseMessage();
response.Content = new PushStreamContent((Stream outputStream, HttpContent content, TransportContext context) =>
{
try
{
DownloadFile(filepath, outputStream);
}
finally
{
outputStream.Close();
}
});
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filepath);
return response;
}
catch (Exception ex)
{
}
return null;
}
public void DownloadFile(string file, Stream response)
{
var bufferSize = 1024 * 1024;
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[bufferSize];
var bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, bufferSize)) > 0)
{
response.Write(buffer, 0, bytesRead);
}
response.Flush();
}
}
}