there.I have been coding in java SE from long time. I am absolute noob in ASP.NET Core MVC and REST API. I have a very basic understanding on the REST. I am working on a requirement which needs to download different types of files from the file path to the local folder.
If the user checks one or more files and then click download then it should be downloaded as a zip file to the local folder.
I have been going through this stackoverflow question but i find it very cluttery Using .NET, how can you find the mime type of a file based on the file signature not the extension
Edit:
Now i have narrowed down the question to only download the PDF files and verify the PDF file.
Adding the coding effort i have done so far to solve this. Now i am stuck with the request and response creation for the rest api to download the file.
Controller class:
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;
}
}
}
}
Class to find if the file is of type PDF:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace FileDownloaderService.Utilities
{
public class FileMimeType
{
//Byte sequence for PDF extensions.
private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
private static readonly string DEFAULT = "application/octet-stream";
//Method to check the file mime type.
public static string GetMimeType(byte[] file,string filename) {
string mime = DEFAULT;
if (string.IsNullOrWhiteSpace(filename)) {
return mime;
}
string extension = Path.GetExtension(filename) == null ? string.Empty : Path.GetExtension(filename).ToUpper();
if (file.Take(7).SequenceEqual(PDF)) {
mime = "application/pdf";
}
return mime;
}
}
}
I am unable to download the file on GET request. Please suggest.