I unziped the file I donwloaded. how and what library do i access in my asp.net mvc 3 app to be able to unzip a file that contains multiple files?
my controller code:
public ActionResult Upload(ScormUploadViewModel model)
{
if (ModelState.IsValid)
{
if (model.ScormPackageFile != null)
{
string zipCurFile = model.ScormPackageFile.FileName;
string fullPath = Path.GetDirectoryName(zipCurFile);
string directoryName = Path.GetFileNameWithoutExtension(zipCurFile);
Directory.CreateDirectory(Path.Combine(fullPath, directoryName));
using (FileStream zipFile = new FileStream(zipCurFile, FileMode.Open))
{
using (GZipStream zipStream = new GZipStream(zipFile, CompressionMode.Decompress))
{
StreamReader reader = new StreamReader(zipStream);
//next unzip the file? how to get the library i need?
}
}
thanks
Related
I converted a .NET Core 3.1 project to .NET 6 and now the download method produces this error:
System.InvalidOperationException: The view 'ExcelDownload' was not found. The following locations were searched:...
This is the method:
public IActionResult ExcelDownload(string TIDList)
{
// ...
// ...
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content, contentType, fileName);
}
}
There has never been a view for this method and it worked with .NET Core 3.1. What's different with .NET 6 that causes this to look for a view?
Using the ClosedXML NuGet to create the Excel file.
Thanks!
Hi you can try FileContentResult
public async Task<FileContentResult> ExcelDownload(string TIDList)
{
var fileProvider = new FileExtensionContentTypeProvider();
if (!fileProvider.TryGetContentType($"{fileName.FileName}{fileName.Extension}", out string contentType))
{
contentType = fileName.Extension.RemoveDot();
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return new FileContentResult(content, contentType)
{
FileDownloadName = fileName
};
}
}
I am using ASP.NET WEB API to upload image to server. But when i upload the source code of my web api to gearhost.com and make a post request. I am unable to post the image. This is my web api controller code:
[Route("upload")]
[HttpPost]
public async Task<string> Upload()
{
var ctx = HttpContext.Current;
var root = ctx.Server.MapPath("/uploads/");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content
.ReadAsMultipartAsync(provider);
foreach (var file in provider.FileData)
{
var name = file.Headers
.ContentDisposition
.FileName;
// remove double quotes from string.
name = name.Trim('"');
var localFileName = file.LocalFileName;
var filePath = Path.Combine(root, "files", name);
// File.Move(localFileName, filePath);
// SaveFilePathSQLServerADO(localFileName, filePath);
// SaveFileBinarySQLServerADO(localFileName, name);
// SaveFilePathSQLServerEF(localFileName, filePath);
SaveFileBinarySQLServerEF(localFileName, name, filePath);
if (File.Exists(localFileName))
File.Delete(localFileName);
}
}
catch
{
return "Error";
}
return "File uploaded successfully!";
}
public void SaveFileBinarySQLServerEF(string localFile, string fileName, string filePath)
{
// 1) Get file binary
byte[] fileBytes;
using (var fs = new FileStream(localFile, FileMode.Open, FileAccess.Read))
{
fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
}
// 2) Create a Files object
var file = new tblimage()
{
Data = fileBytes,
Names = fileName,
ContentType = filePath
};
// 3) Add and save it in database
using (var ctx = new coachEntities())
{
ctx.tblimages.Add(file);
ctx.SaveChanges();
}
}
Here is the successful call from localhost:
Image posted through localhost
However when deployed the same code and make request through postman then I get this error:
Image posted through live server
Maybe, "uploads" doesn't have write permission
Check the permission in your uploads folder.
Go to properties-- security
Give the read write permission.
Though it is not good idea to return the exception details in live code. As you are not maintaining log. For testing, Please return the exception details. Also, how are you getting the response like "unable to upload, try again" because it is not there in your code
Everything is setup well (call method, .xsd file, rdlc file, when i do debugging I can see data in my model, I can download the excel file, but it is still remining empty?! Wher did I'm wrong in my code? Any clue?
My ActionResult in Controller:
[HttpGet]
public ActionResult Export_StudentStatus()
{
List<pr_ReportDataGenerate_AllGeneralOverview_Result> model = Context.pr_ReportDataGenerate_AllGeneralOverview().Where(p => p.rdTypeID == 2).ToList();
ReportViewer viewer = new ReportViewer();
try
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty, encoding = string.Empty, extension = string.Empty;
viewer.ProcessingMode = ProcessingMode.Local;
//viewer.LocalReport.EnableExternalImages = true;
viewer.LocalReport.ReportPath = Server.MapPath("~/RDLC/GeneralOverviewStudentStatus.rdlc");
viewer.LocalReport.DataSources.Add(new ReportDataSource("dsGeneralOverviewAnnualAwards", model));//ova e DS vo reportot
viewer.LocalReport.EnableHyperlinks = true;
byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=GeneralOverviewStudentStatus.xls");
Response.BinaryWrite(bytes);
Response.End();
return null;
}
finally
{
if (viewer != null)
{
viewer.Dispose();
viewer = null;
}
}
}
I am attempting to upload an image using MVC 6; however, I am not able to find the class HttpPostedFileBase. I have checked the GitHub and did not have any luck. Does anyone know the correct way to upload a file in MVC6?
MVC 6 used another mechanism to upload files. You can get more examples on GitHub or other sources. Just use IFormFile as a parameter of your action or a collection of files or IFormFileCollection if you want upload few files in the same time:
public async Task<IActionResult> UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
...
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
...
}
}
You can see current contract of IFormFile in asp.net sources. See also ContentDispositionHeaderValue for additional file info.
There is no HttpPostedFileBase in MVC6. You can use IFormFile instead.
Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs
Snippet from the above link:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
I was searching around for quite a while trying to piece this together in .net core and ended up with the below. The Base64 conversion will be next to be done so that the retrieval and display is a little easier. I have used IFormFileCollection to be able to do multiple files.
[HttpPost]
public async Task<IActionResult> Create(IFormFileCollection files)
{
Models.File fileIn = new Models.File();
if(model != null && files != null)
{
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
byte[] fileBytes = null;
using (var fileStream = file.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
fileIn.Filename = fileName;
fileIn.FileLength = Convert.ToInt32(file.Length);
fileIn.FileType = file.ContentType;
fileIn.FileTypeId = model.FileTypeId;
fileIn.FileData = fileBytes;
_context.Add(fileIn);
await _context.SaveChangesAsync();
}
}
}
return View();
}
EDIT
And below is return of files to a list and then download.
public JsonResult GetAllFiles()
{
var files = _context.File
.Include(a => a.FileCategory)
.Select(a => new
{
id = a.Id.ToString(),
fileName = a.Filename,
fileData = a.FileData,
fileType = a.FileType,
friendlyName = a.FriendlyName,
fileCategory = a.FileCategory.Name.ToLower()
}).ToList();
return Json(files);
}
public FileStreamResult DownloadFileById(int id)
{
// Fetching file encoded code from database.
var file = _context.File.SingleOrDefault(f => f.Id == id);
var fileData = file.FileData;
var fileName = file.Filename;
// Converting to code to byte array
byte[] bytes = Convert.FromBase64String(fileData);
// Converting byte array to memory stream.
MemoryStream stream = new MemoryStream(bytes);
// Create final file stream result.
FileStreamResult fileStream = new FileStreamResult(stream, "*/*");
// File name with file extension.
fileStream.FileDownloadName = fileName;
return fileStream;
}
This code is supposed to download a file using mvc3 controller
public FilePathResult GetFileFromDisk(String file)
{
String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/";
String contentType = "text/plain";
return File(path+file, contentType, file);
}
View part :
#Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null);
But when i click the link I am getting this error
Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.
[DirectoryNotFoundException: Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.]
Why the foldername is repeating in the file path? Please offer a solution...
Try like this:
public ActionResult GetFileFromDisk(string file)
{
var appData = Server.MapPath("~/App_Data");
var path = Path.Combine(appData, file);
path = Path.GetFullPath(path);
if (!path.StartsWith(appData))
{
// Ensure that we are serving file only inside the App_Data folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(path))
{
return HttpNotFound();
}
var contentType = "text/plain";
return File(path, contentType, Path.GetFileName(path));
}