Decompress base64 zipstream - c#

I want to make a plug-in which can transfer the zip file from web to asp.net mvc background and decompress it into my server.
In my website, i choose a zip file
<input type="file" id="FileZip">
and post it's value to my asp.net method
public async Task<string> FileTrs(string Zip)
Then i got the string of the following type
data:application/x-zip-compressed;base64,
How can i unzip it into my server ?
Could anybody tell me, thanks!

I would do something like this and then use for example the SharpZip-lib to decompress my file.
[HttpPost]
public async Task<string> FileTrs()
{
if (Request.Files.Any)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
// Unzip file here with for example SharpZipLib
}
}
}
Examples for how to use SharpZip here
Maybe you need to convert the uploaded file to a stream before using it in the SharpoZipLib.

For .Net Framework 4.5 and higher!! This shall be applicable
Answers how to Unzip, If you have access to server, It shall not be an Issue.
static void Extractor()
{
string whereMyZIPFileIs = #"path\fileName.zip";
string whereIWantToExtract = #"pathOfExtraction";
System.IO.Compression.ZipFile.ExtractToDirectory(whereMyZIPFileIs, whereIWantToExtract);
}
Please add "System.IO.Compression.FileSystem.dll" to Reference

Related

How can I save an image at server in ASP.NET Core MVC using C#? [duplicate]

I'm recently working on a ReactJS app that's calling an API (developed with .NET Core 2.0).
My question is how to use HttpPostedFileBase in an .NET Core 2.0 API in order to get file content and save it in database.
You don't have HttpPostedFileBase in ASP.NET Core 2.0, but you can use IFormFile.
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
More here: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
IFormFile is in the following namespace Microsoft.AspNetCore.Http.
HttpPostedFileBase doesn't exist in ASP.NET Core. You should use IFormFile now, instead. However, that only works when you send the request as multipart/form-data, which you're likely not doing if you're working with a client-side framework like React. If you're posting JSON, you should set the JSON member that corresponds with your file property with the file encoded as a Base64 string. Server-side, you should then bind to byte[].
If anyone finds this by searching for HttpPostedFileBase it's possible you're familiar with writing ASP.NET controller methods something like this:
public async Task<IActionResult> DoThing(MyViewModel model, HttpPostedFileBase fileOne, HttpPostedFileBase fileTwo)
{
//process files here
}
If you're wanting to write an equivalent in ASP.NET Core then you can write it like this:
public async Task<IActionResult> DoThing(MyViewModel model, IFormFile fileOne, IFormFile fileTwo)
{
//process files here
}
i.e. the only change needed to the method signature is replacing HttpPostedFileBase with IFormFile. You will then need to modify your method to work with the new parameter type (e.g. HttpPostedFileBase has an InputStream property, whereas IFormFile has a OpenReadStream() method) but I think the details of those differences are beyond the scope of this question.
You should also be able to get the files like this :
[HttpPost]
public ActionResult UploadFiles()
{
var files = Request.Form.Files;
return Ok();
}

Cannot convert IFormfile to string

I am trying to read a zip file with I get via IFormFile and I am going through the files inside to unzip a selected extension and unzip it but I cannot use the IFormFile to read it. It says cannot convert IFormFile to string.
Any suggestions on how to tackle this?
using (ZipArchive archive = ZipFile.OpenRead(file))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".dbf", StringComparison.OrdinalIgnoreCase))
{
RedirectToAction("Index");
}
}
}
Because IFormFile != string. I guess OpenRead expects a file path.
So, first read the content of the IFormFile into a file, then use that file path.
Although this won't help in this particular case (since ZipFile.OpenRead() expects a file), for those coming here after googling "iformfile to string", you can read an IFormFile into a string, for example as follows:-
var result = new StringBuilder();
using (var reader = new StreamReader(iFormFile.OpenReadStream()))
{
while (reader.Peek() >= 0)
{
result.AppendLine(reader.ReadLine());
}
}

C# .NET Web API What is best practice for file up- and download?

I got a C# .NET Core Web API (REST).
I want to implement an endpoint for upload files and one for download files (any file type, as binary).
What is best practice for design and code? What I find so far by a search engine is kind of week.
Do you have a recommendation for me?
I guess I have to save metadata like the title (type,..?) somewhere else. Could make it easier to search for files.
At this link from microsoft I get the problem, that it seems to be only for MVC API, what I don't use.
After
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
files is empty.
And this from the c-sharpcorner does not work neater. My object file from Type IFormFile doesn't know the method.GetFilename().
If you take a look at the IFormFile docs, you'll notice, that it has a property FileName, which you can use:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile?view=aspnetcore-2.2
So, as an example, you could take that and save it whereever you want with that property. In my case all the low level stuff of writing that file to the storage is hidden in a repository, but you get the idea:
public async Task<IActionResult> Upload(IFormFile file)
{
if (file == null || file.Length == 0) return BadRequest();
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var img = new Entities.Image
{
Name = file.FileName,
ContentType = file.ContentType,
Data = ms.ToArray()
};
await _repo.CreateImage(img);
return Ok();
}
}
There is very nice article about how to upload / download files using .net core at this location. The same tutorial should work for web API also.
I checked in your question that it is not working for you, you many want to check the request through postman / fiddler and check if data is being sent properly. This blog has example of file upload web API
For getting the filename, the definition of IFormFile as as below:
public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
IHeaderDictionary Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
Stream OpenReadStream();
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}
Hence you should be able to use property FileName to get the file name.

How to integated plupload into asp.net MVC2 project

I try to use plupload in my asp.net MVC2 project, can I do it?
Please help me if it can.
Best regards!
it is same as normal file upload but i like plupload i will use on my project so following codes will work with plupload
[HttpPost]
public ActionResult Create(FormCollection collection)
{
// my project need single file upload so i get the first file
// also you can write foreach statement to get all files
HttpPostedFileBase postedFile = Request.Files[0];
Image image = new Image();
if (TryUpdateModel(image))
{
fRepository.AddImage(image);
fRepository.Save();
// Try to save file
if (postedFile.ContentLength > 0)
{
string savePath = Path.Combine(Server.MapPath("~/Content/OtelImages/"), image.ImageID.ToString() +
Path.GetExtension(postedFile.FileName));
postedFile.SaveAs(savePath);
// Path for dbase
image.Path = Path.Combine("Content/OtelImages/", image.ImageID.ToString() +
Path.GetExtension(postedFile.FileName));
}
i didn't change the codes, but if you need any further help please ask, i'll explain

Manipulating freshly uploaded file causes IOException

My Asp.net MVC app requires a file upload. In the course of the upload I'd like to manipulate the freshly uploaded file.
public ActionResult Edit(int id, FormCollection collection) {
Block block = userrep.GetBlock(id);
foreach (string tag in Request.Files) {
var file = Request.Files[tag] as HttpPostedFileBase;
if (file.ContentLength == 0)
continue;
string tempfile = Path.GetTempFileName()
file.SaveAs(tempfile);
// This doesn't seem to make any difference!!
// file.InputStream.Close();
if (FileIsSmallEnough(file)) {
// Will throw an exception!!
File.Move(tempfile, permanentfile);
} else {
GenerateResizedFile(tempfile, permanentfile);
// Will throw an exception!!
File.Delete(tempfile);
}
block.Image = permanentfile;
}
userrep.Save();
The problem with this snippet is that any attempt to manipulate the initially uploaded file generates an IOException("The process cannot access the file because it is being used by another process.") Of course I can bypass the problem by copying rather than moving uploaded file but I still can't delete it once I have a better alternative.
Any advice?
Duffy
As you have mentioned in your comments, you load an Image from file. The MSDN documentation states that the file remains locked until the image is disposed.
http://msdn.microsoft.com/en-us/library/stf701f5.aspx
To dispose your image, you can either call the Dispose method on the instance, or use the preferred mechanism of the using statement:
private bool FileIsSmallEnough()
{
using (Image i = Image.FromFile())
{
}
}
This should solve the problem.

Categories