Displaying mht file in iframe - asp.net

I need to display mht file stored in zip archive in frame on the page
<iframe src="#Url.Action("LoadInstrucion","Pharmacy", new {id= Model.Instrukciya })"></iframe>
Action in MVC Controller returning file
public ActionResult LoadInstrucion(string id)
{
var bytes = InstructionsLoader.LoadInstrucion(id);
return File(bytes, "multipart/related");
}
Action for getting byte array from file
public static byte[] LoadInstrucion(string zipFileName)
{
string zipfilePath = $#"{HttpContext.Current.Request.PhysicalApplicationPath}Content\inst\{zipFileName}.zip";
if (File.Exists(zipfilePath))
{
using (var zipStream = new FileStream(zipfilePath, FileMode.Open))
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
if (archive.Entries.Count > 0)
{
var file = archive.Entries[0];
var stream = file.Open();
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
}
return new byte[0];
}
If I navigate to Url I see the requested mht file, but it is not displayed in iframe. In Dev console I get warning:
Attempted to load a multipart archive into an subframe

Related

Asp.Net MVC download varbinary stored in database as file

i want to download varbinary stored in database as a file. I am able to download the file, however all the file that downloaded from my application are unable to open. I noticed that i upload pdf file with size 200 kb. But when i download that file, its only return 30 byte.
Here is the code:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Upload(Upload model, HttpPostedFileBase uploadFile, String random_number, String rcf_number)
{
var db = new RCFOnlineEntities();
if(uploadFile != null)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
{
bytes = br.ReadBytes(uploadFile.ContentLength);
}
model.file_base6 = bytes;
model.file_ext = uploadFile.ContentType;
model.file_name = uploadFile.FileName;
model.rcfnumber = rcf_number;
model.randomnumber = random_number;
}
db.Uploads.Add(model);
db.SaveChanges();
return RedirectToAction("Edit", "GetRCFOnline", new { random_number = random_number });
}
[HttpGet]
public FileResult DownLoadFile(int id, String random_number)
{
List<Upload> ObjFiles = GetUploadClasses(random_number);
var FileById = (from FC in ObjFiles
where FC.file_id.Equals(id)
select new { FC.file_name, FC.file_base6 , FC.file_ext}).ToList().FirstOrDefault();
return File(FileById.file_base6, FileById.file_ext, FileById.file_name);
}
Could you tell me where is the error within my code ?
Solution-1:
Use uploadFile.InputStream.Length instead uploadFile.ContentLength for correct upload file size i.e.
using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
{
bytes = br.ReadBytes(uploadFile.InputStream.Length);
}
Solution-2:
If BinaryReader is not a fixed requirement then use below solution to get uploaded file's bytes i.e.
byte[] bytes = new byte[uploadFile.InputStream.Length];
uploadFile.InputStream.Read(bytes, 0, bytes.Length);

ASP.NET Core Image Resize

I'm trying to resize imagine with System.Drawing but im taking that file as IFormFile and when i use the System.Drawing its just keep warning me to about that : cannot implicitly convert type 'System.Drawing.Bitmap' to 'Microsoft.AspNetCore.Http.IFormFile' . I need to resize those photos and save them as IFormFile but i dont know how to do that.
public Task<IFormFile> ResizeImagine300x300(IFormFile file)
{
Image image = Image.FromStream(file.OpenReadStream(), true, true);
var newImage = new Bitmap(1024, 768);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, 1024, 768);
};
return newImage;//the point where i get the error
}
Is it possible to do it in my way?
If its not possible, then which way i should follow?
Thanks for any suggestion
Edit: I wanna return as a IFormFile because i have a method which is uploading those files to my database. here is my method :
public async Task<FileRepo> FileUploadToDatabase(List<IFormFile> files)
{
foreach (var file in files)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
_fileRepo = new FileRepo
{
FileName = fileName,
FileExtension = fileExtension,
FileType = file.ContentType,
CreatedDate= DateTime.Now
};
using (var dataStream = new MemoryStream())
{
await file.CopyToAsync(dataStream);
_fileRepo.FileData = dataStream.ToArray();
}
}
return _fileRepo;
}
After that I'm uploading that _fileRepo variable to my database like that :
var File = _fileUploader.FileUploadToDatabase(files);
var FileResult = File.Result;
FileResult.ProductID = ProductID;
_unitOfWorkFR.RepositoryFileRepo.Create(FileResult);

Return a file from asp.net web api

I've been trying to return a file from my web api. Below is my code somehow downloads the file, but the downloaded file is corrupted.
SomeMethod
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(response.FileArray.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
public HttpResponseMessage Download([FromUri] DownloadRequest req) { }

Get FileStream from form posted file

I have a control on view page. When user selects the file and clicks on submit button this makes ajax call to upload the file on server. Unfortunately my server method accepts file path (like C:/Videos/1.mp4) to upload. This works great with string demoPath in the code below but I'm not sure how to get similar path when user selects in control. Due to sercurity reasons modern browsers not allows exposing paths. How to achieve this?
[HttpPost]
public async Task<JsonResult> Upload(string lectureId, string filepath)
{
for (int i = 0; i < Request.Files.Count; i++)
{
//// This works great
//string demoPath = "C:/Users/abchi/Desktop/BigBuckBunny.mp4";
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
//var path = Path.Combine(Server.MapPath("~/User/"), fileName);
//file.SaveAs(path);
//await RunUploader(demoPath);
await RunUploader(get_path_from_posted_file_or_request);
}
return Json(new { error = false, message = "Video uploaded." });
}
public async Task RunUploader(string filePath)
{
// :::::::
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
// ::::
}
// ::::::
}
I'm not sure this is expected because I did not quite understand.
Download the file path of the user's computer can not be - https://stackoverflow.com/a/15201258/4599089
but if you want to have access to the FileStream on your server:
File has InputStream and you can use this:
[HttpPost]
public async Task<JsonResult> Upload(string lectureId, string filepath)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/User/"), fileName);
var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
file.InputStream.CopyTo(fileStream);
fileStream.Close();
await RunUploader(path); //path or stream
}
return Json(new { error = false, message = "Video uploaded." });
}
public async Task RunUploader(string filePath)
{
// :::::::
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
// ::::
}
// ::::::
}
I asked my fellow dev to make necessary changes in public async Task RunUploader(string filePath) parameters. Said code was part of YouTube .NET samples for console apps. Now we are developing for web, in this case we can't pass full path. So they made following changes:
[HttpPost]
public async Task<JsonResult> Upload(string lectureId)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
Stream fileStream = file.InputStream;
await Run(fileStream);
}
return Json(new { error = false, message = "Video uploaded." });
}
public async Task Run(Stream fileStream)
{
// ::::::::::
using (fileStream)
{
// ::::::
}
// ::::::::::
}
Now with this change everything started working.

Embedding text file in asp.net project

I added text file to my web project. Right click and clicking on properties
menu I choose ,Build Action -> Resource.
How can I retrieve the content of the file in my code behind page.
I try this but I received stream null
internal string GetFromResources(string resourceName)
{
Assembly assem = this.GetType().Assembly;
using (Stream stream = assem.GetManifestResourceStream(resourceName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
But it's not working.
Please help
Try changing the Build Action to Embedded Resource and make sure that the resource name contains the namespace. i.e.
MyProjectNamespace.MyTextFileName.txt
If your file is in a sub folder then use:
MyProjectNamespace.SubFolderName.MyTextFileName.txt
I solved it, below are the steps that I took.
First of all I defined text file as embedded resource.
Second problem was that I did not added assembly name space to the text file.
So I changed the function and added namespace
internal string GetFromResources(string resourceName)
{
Assembly assem = this.GetType().Assembly;
**List<string> listNameSpaces = assem.GetTypes().Select(t => t.Namespace).Distinct().ToList<string>();**
foreach (string ns in listNameSpaces)
{
**string nsResourceName = ns + "." + resourceName;**
using (Stream stream = assem.GetManifestResourceStream(nsResourceName))
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
return string.Empty;
}

Resources