REST API:从后端服务器的前端下载文件

时间:2017-06-19 06:59:42

标签: c# asp.net rest file download

那里。我一直在java SE中编码。我是ASP.NET Core MVC和REST API中的绝对菜鸟。我对REST有一个非常基本的了解。我正在制定一项要求,需要从文件路径下载不同类型的文件到本地文件夹。

如果用户检查一个或多个文件然后单击下载,则应将其作为zip文件下载到本地文件夹。

我一直在经历这个stackoverflow问题,但我发现它非常混乱 Using .NET, how can you find the mime type of a file based on the file signature not the extension

修改

现在我已将问题范围缩小到只下载PDF文件并验证PDF文件。

添加我迄今为止所做的编码工作来解决这个问题。现在我坚持为其余的api下载文件的请求和响应创建。

控制器类:

sex

查找文件是否为PDF类型的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;


namespace FileDownloaderService.Controllers
{
    public class FileDownloadController : Controller
    {
        [HttpGet]
    public HttpResponseMessage Get() {
        string filename = "ASPNETCore" + ".pdf";
        string path = @"C:\path_to_file\"+ filename;

        if (System.IO.File.Exists(path)) {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(path, FileMode.Open,FileAccess.Read);
            stream.Position = 0;
            response.Content = new StreamContent(stream);
            response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
            response.Content.Headers.ContentDisposition.FileName = filename;
            return response;
        }
        else
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Gone);
            return response;
        }
    }

    }
}

我无法在GET请求中下载该文件。请建议。

0 个答案:

没有答案