Hi there i have created a zipfile and i want to upload it after it has been created.
I have a method to upload the file but it only accepts the file in as a HttpPostedFileBase.
After my zip file is saved how would i go about changing it into a HttpPostedFileBase so that i can pass it to my upload method.
using (ZipFile zip = new ZipFile())
{
// add this map to zip
zip.AddFile(tempFolderPath + PropInfo[7].TagValue, "");
zip.AddFile(tempFolderPath + "data.xml", "");
zip.AddFile(tempFolderPath + "dvform.dvform", "");
zip.AddFile(tempFolderPath + "CS1.pdf", "");
zip.AddFile(tempFolderPath + "CS2.pdf", "");
zip.AddFile(tempFolderPath + "CS3.pdf", "");
zip.AddFile(tempFolderPath + "CS4.pdf", "");
zip.AddFile(tempFolderPath + "CS5.pdf", "");
zip.Save(tempFolderPath + "Tester.xap"); //Xap Save Name
}
If you really want to make a zip file into HttpPostedFileBase then your best option is probably to create a class that inherits from HttpPostedFileBase and override the methods as needed.
There aren't many things to override and they should all be pretty simple to get from a file object (they are filename, contentlength and contenttype as well as the filestream itself).
By far the best thing to do would be to refactor your upload method to not need a HttpPostedFileBase object. Make it take a more usual file object or stream or similar (depending on what the upload needs) and then create an override that takes a HttpPostedFileBase and extracts the bits it needs to pass to your main upload method.
Refactoring the upload method is probably beyond the scope of this question though.
Just an Idea, hope you can build on this
HttpPostedFile f = new HttpPostedFile();
f.InputStream = new System.IO.FileStream(); //replace this with Stream from your zip
HttpPostedFileBase zipFile = new HttpPostedFileWrapper(f);
Related
I have an API Upload Controller, which has a parameter IFormFile. From Swagger, I am passing a .zip file which has a few .json files inside. I want to get these .json files from that .zip that I receive from Swagger and pass them to a service that will process them.
So I managed to create a logic like this. I save the .zip file in (~Temp>settings) directory, the next thing I want to do is unzip that file and send the .json files into a different directory named "temp-json-imports". So then I can get the .json files and work with them.
Here is the code that I have written so far, this doesn't work, it fails on the last line - (ZipFile.ExtractToDirectory(filePath, tmpJsonImports);), with an exception of type System.IO.IOException (like shown in the picture below).
Any ideas on how can I solve this problem would be very much welcome. :)
[HttpPost("import/{applicationId}")]
public async Task<IActionResult> ImportSettings([FromRoute] Guid applicationId, IFormFile file)
{
string tempPath = Path.Combine(_hostingEnvironment.ContentRootPath, Path.GetTempPath());
string tmpSettingsPath = Path.Combine(tempPath, "settings");
string tmpImportSettings = Path.Combine(tmpSettingsPath, "import");
string tmpJsonImports = Path.Combine(tmpImportSettings, "temp-json-imports");
Directory.CreateDirectory(tmpSettingsPath);
Directory.CreateDirectory(tmpImportSettings);
Directory.CreateDirectory(tmpJsonImports);
long size = file.Length;
if (size > 0)
{
var filePath = tmpImportSettings + "\\" + file.FileName;
using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
string zipPath = Path.GetFileName(filePath);
ZipFile.ExtractToDirectory(filePath, tmpJsonImports);
}
return Ok();
}
Try to use your code on my application, it will show this exception:
This exception relates the following code, you didn't close the file handle after copy the file to the path.
var filePath = tmpImportSettings + "\\" + file.FileName;
using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
To solve this exception, try to modify your code as below:
if (size > 0)
{
var filePath = tmpImportSettings + "\\" + fileviewmodel.File.FileName;
using (var stream = new FileStream(filePath, FileMode.Create))
{
await fileviewmodel.File.CopyToAsync(stream);
};
string zipPath = Path.GetFileName(filePath);
ZipFile.ExtractToDirectory(filePath, tmpJsonImports);
}
I have to ask a suggestion about a project I'm following. I need to create an action inside an MVC controller that let me download a series of images directly and not by compressing them inside a zip archive. I tried to achieve that by calling a download function inside the action, like this:
foreach(var image in images){
var imageFilename = image.filename;
var imageName = image.text;
var mimeType = image.type;
DownloadFile(imageFilename, imageName, mimeType);
}
Setting download file as
public FileResult DownloadFile(string imageFilename, string imageName, string mimeType){
return File(imageFilename, imageName, mimeType);
}
But this not works. Do you have any suggestion on how to proceed on this to avoid zip archive? Or is the only suitable method for this problem?
I am using html input file to upload the files. Everything is working fine except in the case of .Zip or .rar. I am checking posted file in generic handler like:
HttpPostedFile PostedFile = context.Request.Files[0];
if (!(PostedFile == null))
{
//do processing..
}
I tried image files, pdf, doc, even sql query files. Every type is uploading well, but with the case of .rar or .zip files I am not getting posted file into ashx handler. I mean every time I get an object reference not set to an instance of an object error.
I wonder how could I can post the .rar files or .zip files to handler. I am appending data in client side using form data like:
var form = $("#form1")[0];
var formdata = new FormData(form);
formdata.append('Data', JSON.stringify({ objEnt: args }));
Check if you get the file contents in the context.Request.InputStream. If yes then you can use following code:
if (context.Request.InputStream != null && context.Request.InputStream.Length > 0)
{
System.IO.Stream fileContent = context.Request.InputStream;
System.IO.FileStream fileStream = System.IO.File.Create(Server.MapPath("~/") + fileName);
fileContent.Seek(0, System.IO.SeekOrigin.Begin);
fileContent.CopyTo(fileStream);
}
I'm trying to get the metadata from an absolute URL to a song, such as http://www.<url>.com/<file>.mp3
How do I go about doing this. I'm a little new to the C# api's so I'm a little lost in terms of what classes to use.
I found this block of code from searching around:
StorageFile newFile = //file
var prop =await newFile.Properties.GetMusicPropertiesAsync();
string album = prop.Album;
and I was wondering what goes in the //file field? What class is of type StorageFile that will take in a URI?
Thank you.
First, you can download the mp3 file to local using this:
WebClient Client = new WebClient ();
Client.DownloadFile("http://myserver.com/indie/band1.mp3", "band1.mp3");
Then, use TagLibSharp https://github.com/mono/taglib-sharp
//Local reference to the file
TagLib.File file = TagLib.File.Create("band1.mp3");
//Get the file metadata
Console.WriteLine("Tags on disk: " + file.TagTypesOnDisk);
Console.WriteLine("Tags in object: " + file.TagTypes);
Write ("Grouping", file.Tag.Grouping);
Write ("Title", file.Tag.Title);
Write ("Album Artists", file.Tag.AlbumArtists);
Write ("Performers", file.Tag.Performers);
Write ("Composers", file.Tag.Composers);
Write ("Conductor", file.Tag.Conductor);
Write ("Album", file.Tag.Album);
Write ("Genres", file.Tag.Genres);
Write ("BPM", file.Tag.BeatsPerMinute);
Write ("Year", file.Tag.Year);
Write ("Track", file.Tag.Track);
Write ("TrackCount", file.Tag.TrackCount);
Write ("Disc", file.Tag.Disc);
Write ("DiscCount", file.Tag.DiscCount);
I have many file types: pdf, tiff, jpeg, bmp. etc.
My question is how can I change file extension?
I tried this:
my file= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
No matter what type of file it is, the format I specify must be with the file name. But it does not work. I get file path from browser like c:\..\..\a.jpg, and the file format is a.jpeg. So, when I try to delete it, it gives me an error: Cannot find the file on specified path'. So, I am thinking it has something to do with the file extension that does not match. So, I am trying to convert .jpg to .jpeg and delete the file then.
There is: Path.ChangeExtension method. E.g.:
var result = Path.ChangeExtension(myffile, ".jpg");
In the case if you also want to physically change the extension, you could use File.Move method:
File.Move(myffile, Path.ChangeExtension(myffile, ".jpg"));
You should do a move of the file to rename it. In your example code you are only changing the string, not the file:
myfile= "c:/my documents/my images/cars/a.jpg";
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
you are only changing myfile (which is a string). To move the actual file, you should do
FileInfo f = new FileInfo(myfile);
f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));
See FileInfo.MoveTo
try this.
filename = Path.ChangeExtension(".blah")
in you Case:
myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah")
You should look this post too:
http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx
The method GetFileNameWithoutExtension, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
Convert file format to png
string newfilename ,
string filename = "~/Photo/" + lbl_ImgPath.Text.ToString();/*get filename from specific path where we store image*/
string newfilename = Path.ChangeExtension(filename, ".png");/*Convert file format from jpg to png*/
Alternative to using Path.ChangeExtension
string ChangeFileExtension(ReadOnlySpan<char> path, ReadOnlySpan<char> extension)
{
var lastPeriod = path.LastIndexOf('.');
return string.Concat(path[..lastPeriod], extension);
}
string myfile= #"C:/my documents/my images/cars/a.jpg";
string changedFileExtesion = ChangeFileExtension(myfile, ".jpeg");
Console.WriteLine(changedFileExtesion);
// output: C:/my documents/my images/cars/a.jpeg