我正在使用ASP.NET MVC的新的WebAPI的网络服务,将成为了二进制文件,主要是.cab
和.exe
文件.
以下控制器方法似乎有效,这意味着它返回一个文件,但它将内容类型设置为application/json
:
public HttpResponseMessage<Stream> Post(string version, string environment, string filetype)
{
var path = @"C:\Temp\test.exe";
var stream = new FileStream(path, FileMode.Open);
return new HttpResponseMessage<Stream>(stream, new MediaTypeHeaderValue("application/octet-stream"));
}
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
我刚刚将项目从 ASP.Net 4.5 迁移到 ASP.Net Core。我有一个 REST API get,过去用于返回 blob,但现在返回 JSON。
这是旧代码:
[HttpGet]
[ResponseType(typeof(HttpResponseMessage))]
[Route("Download/{documentId}")]
public async Task<HttpResponseMessage> DownloadDocument(string documentId)
{
try
{
var result = await TheDocumentService.DownloadDocument(documentId);
return result;
}
catch (Exception ex)
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent(ex.Message)
};
}
}
Run Code Online (Sandbox Code Playgroud)
ASP.net Core 中的代码除了[ResponseType(typeof(HttpResponseMessage))]
在 ASP.Net Core 中不起作用之外是相同的,并且两种解决方案的返回结果也相同。
但是当在客户端查看服务器的响应时,它们是不同的。
因此,它们之间唯一的区别是[ResponseType(typeof(HttpResponseMessage))]
. ASP.NET Core 中有类似的东西吗?
我正在尝试使用 Blazor 做一些事情,但我还是个新手。我正在尝试获取文件流以下载到浏览器。将文件从 Blazor 下载到浏览器的最佳方式是什么?
我试过在我的剃刀视图中使用一种方法来返回一个流,但没有用。
//In my Blazor view
@code{
private FileStream Download()
{
//get path + file name
var file = @"c:\path\to\my\file\test.txt";
var stream = new FileStream(test, FileMode.OpenOrCreate);
return stream;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有给我任何东西,甚至没有错误
我已经搜索了一段时间,虽然它应该很简单,但我就是无法让它工作。根据我见过的例子,这是我到目前为止得到的:
SomeAppService.cs
public async Task<FileStream> Download(long? id)
{
var attachment = await _repository.FirstOrDefaultAsync(x => x.Id == id);
var fileStream = new FileStream($"{attachment.FileName}.{attachment.FileExtension}",
FileMode.Create, FileAccess.Write);
fileStream.Write(attachment.File, 0, attachment.File.Length);
return fileStream;
}
Run Code Online (Sandbox Code Playgroud)
可以注意到,“FileName”、“FileExtension”和“File”(即前述的字节数组)存储在数据库中。附件可以是任何类型的文件,但上传方法中禁止的扩展名除外(未显示)。然后在我的控制器中我有:
SomeController.cs
[AllowAnonymous]
[HttpGet("Download/{id}")]
public async Task<IActionResult> Download(long? id)
{
var fileStream = await appService.Download(id);
return new FileStreamResult(fileStream, "application/octet-stream");
}
Run Code Online (Sandbox Code Playgroud)
然而,当我到达下载端点时,我最终得到一个名为“response”的文件,没有扩展名,大小为 0 字节。
资源:
将 MemoryStream 保存到文件或从文件加载(255 个赞成票的响应让我了解了如何将字节数组转换为文件流,但我不知道这是否有效)
我已经编写了一个控制器来下载/流文件到客户端本地机器.除了只生成响应体之外,代码不会在对URL进行GET时传输文件.
streamcontent方法有什么问题.在调试我找不到问题.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;
namespace FileDownloaderService.Controllers
{
[Route("api/[controller]")]
public class FileDownloadController : Controller
{
[HttpGet]
public HttpResponseMessage Get() {
string filename = "ASPNETCore" + ".pdf";
string path = @"C:\Users\INPYADAV\Documents\LearningMaterial\"+ filename;
if (System.IO.File.Exists(path)) {
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
stream.Position = 0;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"); …
Run Code Online (Sandbox Code Playgroud) 我正在尝试从服务器下载文件,但该文件并未显示其原始内容,而是显示 [object Object]。
WEB API 核心
[Authorize(AuthenticationSchemes = "Bearer")]
[HttpGet]
public HttpResponseMessage DownloadContractFile(string fileName)
{
string contentRootPath = _hostingEnvironment.ContentRootPath;
var folderName = Path.Combine(contentRootPath, FileHandler.ContractFilePath, Convert.ToInt32(User.Identity.Name).ToString());
var path = Path.Combine(folderName, fileName);
var memory = new MemoryStream();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var stream = new FileStream(path, FileMode.Open))
{
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(FileHandler.GetContentType(path)); // Text file
result.Content.Headers.ContentLength = stream.Length;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
Angular 代码:服务方法
downloadContractFile(fileName: string) {
const obj: …
Run Code Online (Sandbox Code Playgroud) c# asp.net-web-api asp.net-core asp.net-core-webapi angular7
我的目标是 GET 和 POST 文件到 SP Online。
我用这两种方法编写了一个 WEB API。这些方法使用 CSOM 与 SP Online 进行交互。
GET 将响应 Ok(字节数组)返回给客户端,POST 获取要在请求正文中上传的整个文件,并以块的形式执行上传到 Sharepoint Online。
有人告诉我,我应该使用流技术,因为上下文是具有许多同时请求的企业应用程序。所以 GET 方法应该向客户端返回一个流,客户端应该将请求作为流发送到 POST。
在客户端,我被迫使用 RestSharp 库。
所以:
1)如何使用RestSharp来处理流?
2) WebAPI 如何返回流?
3)随着文件,我发送了很多元数据。如何以流模式上传文件并只发送一次元数据?
客户端,get 需要一个字节数组,post 发送一个字节数组和元数据。
在网上我发现了太多的技巧。有标准的吗?
我的控制器中有这个方法。
public IActionResult Download()
{
return Json(_context.Users);
}
Run Code Online (Sandbox Code Playgroud)
我注意到它生成了正确的 JSON 结构,但它在浏览器中呈现为通用文本。我希望将其下载到客户的计算机上。我怎么做?
我不确定是否应该使我的对象以某种方式进行流式传输,或者在我的硬盘驱动器上创建一个文件并像这样提供它。
我找不到任何让我印象深刻的东西,就像我们在 C# 中所习惯的那样直接、简单。所以我担心我在这里遗漏了一个概念。
大家好
我正在尝试从Axios Request从ASP.NET Core Web API下载文件。
这是我的示例API方法。(基于此stackoverflow问题的代码)
[HttpPost("download")]
public async Task<IActionResult> DownloadFile(){
...
return File(new MemoryStream(mypdfbyte), "application/octet-stream", "myfile.pdf");
}
Run Code Online (Sandbox Code Playgroud)
这是我的示例axios请求。
axios.post(`api/products/download`).then(response=>{
console.log(response.data)
}).catch(error=>{ console.log(error) })
Run Code Online (Sandbox Code Playgroud)
但是我只收到这个。没有下载文件出现。
希望您能帮助我从控制器api下载文件。
我发现了一堆示例,这些示例使用了我在应用程序中不可用的对象,并且似乎与我的 .NET Core Web API 版本不匹配。本质上,我正在开发一个项目,该项目在网页上有标签,并希望使用服务器中的流加载视频,而不是通过路径直接提供文件。原因之一是文件的来源可能会发生变化,并且通过路径提供它们并不是我的客户想要的。所以我需要能够打开流并异步写入视频文件。
由于某种原因,这会生成 JSON 数据,因此这是错误的。我正在从 Azure Blob 存储下载视频文件并作为流返回,但我只是不明白需要做什么才能将流式视频文件发送到 HTML 中的标记。
我的 API 控制器,
[AllowAnonymous]
[HttpGet("getintroductoryvideos")]
public async Task<Stream> GetIntroductoryVideos()
{
try
{
return _documentsService.WriteContentToStream().Result;
}
catch (Exception ex)
{
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务班,
public async Task<Stream> WriteContentToStream()
{
var cloudBlob = await _blobService.GetBlobAsync(PlatformServiceConstants._blobIntroductoryVideoContainerPath + PlatformServiceConstants.IntroductoryVideo1, introductoryvideocontainerName);
await cloudBlob.FetchAttributesAsync();
var fileStream = new MemoryStream();
await cloudBlob.DownloadToStreamAsync(fileStream);
return fileStream;
}
Run Code Online (Sandbox Code Playgroud) c# ×9
asp.net-core ×4
asp.net ×3
asp.net-mvc ×2
.net ×1
angular7 ×1
axios ×1
azure ×1
blazor ×1
browser ×1
download ×1
file ×1
filestream ×1
html5-video ×1
restsharp ×1