this code works once in server and after that again we click the submit button server shows "www.example.com can't currently handle this request.
HTTP ERROR 500"
This is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("AboutId,Title,ImagePath,ShortContent,LongContent,RecordStatus,CreatedDate,Seokeywords")] AboutTbl aboutTbl, IFormFile FormFile)
{
if (ModelState.IsValid)
{
//----
string newFileName;
var fileName = ContentDispositionHeaderValue.Parse(FormFile.ContentDisposition).FileName.Trim('"');
int index = fileName.LastIndexOf('.');
string onlyName = fileName.Substring(0, index);
string fileExtension = fileName.Substring(index + 1);
var abtrepo = _aboutTblRepository.FindwithImagePath(fileName);
if (abtrepo != null)
{
newFileName = onlyName + DateTime.Now.ToString("yyyy-MM-ddHHmmtt") + "." + fileExtension;
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", newFileName);
aboutTbl.ImagePath = newFileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
else
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", FormFile.FileName);
aboutTbl.ImagePath = fileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
//----
byte recordStatus = (byte)Common.CommonEnums.RecordStatus.ACTIVE;
aboutTbl.RecordStatus = (byte?)recordStatus;
DateTime createdDate = DateTime.Now;
aboutTbl.CreatedDate = createdDate;
_aboutTblRepository.CreateAbout(aboutTbl);
_notyf.Success("About added successfully");
return RedirectToAction(nameof(Index));
}
return View(aboutTbl);
}
this is AboutTblRepository
public void CreateAbout(AboutTbl aboutTbl)
{
_context.Add(aboutTbl);
_context.SaveChanges();
}
Interface IAboutTblRepository
public void CreateAbout (AboutTbl aboutTbl);
Recently i found that error
i just removed
var abtrepo = _aboutTblRepository.FindwithImagePath(fileName);
if (abtrepo != null)
{
}
else
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "About", FormFile.FileName);
aboutTbl.ImagePath = fileName;
using (System.IO.Stream stream = new FileStream(filePath, FileMode.Create))
{
FormFile.CopyTo(stream);
}
}
Related
My files are in blob storage.So how i can download the multiple files from folder as zip
I am trying this code from some time it is working but not giving me output.Means its not starting the zip download.:
string zipFileName = "MyZipFiles.zip";
using (var zipOutputStream = new
ZipOutputStream(HttpContext.Current.Response.OutputStream))
{
zipOutputStream.SetLevel(0);
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
HttpContext.Current.Response.ContentType = "application/zip";
foreach (var filePath in fileUrl)
{
var filename = Path.GetFileName(filePath.filename);
var filebytes = filePath.filebyte.BlobByteArray;
var fileEntry = new ZipEntry(Path.GetFileName(filePath.filename))
{
Size = filebytes.Length
};
zipOutputStream.PutNextEntry(fileEntry);
zipOutputStream.Write(filebytes, 0, filebytes.Length);
}
zipOutputStream.Flush();
zipOutputStream.Close();
}
My file url contains:
foreach (var item in obj)
{
em = new FileUrlForbyte();
em.filename = item.FileName;
em.url = objBlobHelper.GetFileByFileNameMultiple(item.ContainerName, item.SubFolderName + "/" + item.FileName, DateTime.Now.AddMinutes(2));
em.filebyte = objBlobHelper.DownloadFileByFileNameForAdobe(item.ContainerName, item.SubFolderName + "/" + item.FileName);
fileUrl.Add(em);
}
FOr more clarity:filePath contains:filename,fileurl and file byte:
[Route("api/Blob/getMultipleFileFromBlobByURI")]
[HttpGet]
public System.Web.Mvc.FileResult getMultipleFileFromBlobByURI(string containerName)
{
List<BlobStorageModel> obj = new JavaScriptSerializer().Deserialize<List<BlobStorageModel>>(containerName);
try
{
BlobHelper objBlobHelper = new BlobHelper(apiPrincipal);
List<FileUrlForbyte> fileUrl = new List<FileUrlForbyte>();
FileUrlForbyte em = new FileUrlForbyte();
foreach (var item in obj)
{
em = new FileUrlForbyte();
em.filename = item.FileName;
em.url = objBlobHelper.GetFileByFileNameMultiple(item.ContainerName, item.SubFolderName + "/" + item.FileName, DateTime.Now.AddMinutes(2));
em.filebyte = objBlobHelper.DownloadFileByFileNameForAdobe(item.ContainerName, item.SubFolderName + "/" + item.FileName);
fileUrl.Add(em);
}
// Here we will create zip file & download
string zipFileName = "MyZipFiles.zip";
var fileName = string.Format("{0}_ImageFiles.zip", DateTime.Today.Date.ToString("dd-MM-yyyy") + "_1");
var tempOutPutPath = System.Web.HttpContext.Current.Server.MapPath(Url.Content("/TempImages/")) + fileName;
try
{
using (var zipOutputStream = new ZipOutputStream(HttpContext.Current.Response.OutputStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
HttpContext.Current.Response.ContentType = "application/zip";
foreach (var filePath in fileUrl)
{
var filename = Path.GetFileName(filePath.filename);
var filebytes = filePath.filebyte.BlobByteArray;
var fileEntry = new ZipEntry(Path.GetFileName(filePath.filename))
{
Size = filebytes.Length
};
zipOutputStream.PutNextEntry(fileEntry);
zipOutputStream.Write(filebytes, 0, filebytes.Length);
}
zipOutputStream.Finish();
zipOutputStream.Flush();
zipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutPutPath);
if (System.IO.File.Exists(tempOutPutPath))
System.IO.File.Delete(tempOutPutPath);
if (finalResult == null || !finalResult.Any())
throw new Exception(String.Format("No Files found with Image"));
return new System.IO.File(finalResult, "application/zip", fileName);
}
catch (Exception)
{
throw;
}
}
catch (Exception)
{
throw;
}
}
Thanks #Sudheer for your inputs in the comments.
I am trying this code from some time it is working but not giving me output.Means its not starting the zip download.: string zipFileName = “MyZipFiles.zip”;
Referring to the above comment I have tried the below code and was able to execute it successfully.
CloudStorageAccount storage_Account = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudBlobClient blob_Client = storage_Account.CreateCloudBlobClient();
CloudBlobContainer container = blob_Client.GetContainerReference(container_Name);
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename);
Stream file = File.OpenWrite(#"C:\Tools\" + filename);
cloudBlockBlob.DownloadToStream(file);
Console.WriteLine("Download completed!");
Then, I have created a container in my storage account as shown below.
We need to upload the zip file into the above folder and run the given code.
Now I can see that I can access my container and download the zip file located inside the container.
I am trying to upload a .png file using below source code. These codes are executed successfully without having any error and Directory also created as per the mentioned path. But file is not being uploaded on that path.
public bool SaveFile(string Filepath, string FileContainer, string FileNewName)
{
IMMAuthenticationManager iMMAuthenticationManager = null;
IConfiguration iConfig = null;
FileUtility FU = new FileUtility(iMMAuthenticationManager, iConfig);
var file = HttpContext.Request.Form.Files[FileContainer];
bool FileData = FU.FileUtilityUpload2(Filepath, file, FileNewName);
return FileData;
}
public bool FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
string fileSavePath = Path.Combine(path, FileNewName);
MemoryStream streamfileSavePath = new MemoryStream(Encoding.UTF8.GetBytes(fileSavePath));
file.CopyToAsync(streamfileSavePath);
return true;
}
}
return false;
}
Here value of fileSavePath is C:\\Development\MedicalMonitor\Task\DEMO1001\Task1666027260354.png.
Is there any mistake in the above code?
If you want to use MemoryStream upload file, You can use this code:
public bool FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
//var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
using (MemoryStream streamfileSavePath = new MemoryStream())
{
string fileSavePath = Path.Combine(path, FileNewName);
using (var fs = new FileStream(fileSavePath, FileMode.Create, FileAccess.Write))
{
streamfileSavePath.WriteTo(streamfileSavePath);
}
}
return true;
}
}
return false;
}
Or, You can also use the asynchronous method recommended by the Microsoft Docs, it is simpler
public async Task<bool> FileUtilityUpload2(string path, IFormFile file, string FileNewName)
{
if (file != null)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
//uniqueName = Guid.NewGuid().ToString() + ext;
string fileSavePath = Path.Combine(path, FileNewName);
using (var stream = System.IO.File.Create(fileSavePath))
{
await file.CopyToAsync(stream);
}
return true;
}
}
return false;
}
Then in SaveFile:
public bool SaveFile(string Filepath, string FileContainer, string FileNewName)
{
//............
bool FileData = FileUtilityUpload2(Filepath, file, FileNewName).IsCompleted;
return FileData;
}
As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
s.Finish();
s.Close();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.
I want to download a file from the server, but I don't understand what I'm doing wrong. I've been searching how to do it, but doesn't work. This is an example that I found:
Controller (ASP NET MVC):
public HttpResponseMessage GetFile(string filename)
{
try
{
if (!string.IsNullOrEmpty(filename))
{
//string filePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Documentos"));
string filePath = dirInfo.FullName + #"\" + filename;
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray());
httpResponseMessage.Content.Headers.Add("x-filename", filename);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");//application/octet-stream
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = file.Name;
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
angular controller:
$scope.downloadFiles = function () {
var filename = "aae49c8e-c523-4ccc-a7ba-88f405072047&file.pdf";
$http({
method: 'GET',
url: 'serv/Consultas/GetFile',
params: { filename: filename },
responseType: "arraybuffer"
}).success(function (response) {
var file = new Blob([(response)], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
}).error(function (data, status) {
console.log("Request failed with status: " + status);
});
}
When I load the file I just get the filename incomplete "aae49c8e-c523-4ccc-a7ba-88f405072047" and don't load the file. Thanks for any help.
Stream the file from the server:
public FileStreamResult GetFile(string filename)
{
try
{
if (!string.IsNullOrEmpty(filename))
{
//string filePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Documentos"));
string filePath = dirInfo.FullName + #"\" + filename;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
Open new window with URL to action method that will STREAM the PDF so that it can be shown in the browser:
var fileURL = 'serv/Consultas/GetFile?filename=file.pdf';
$window.open(fileURL);
I want to read Excel file from JSON data which I am sending from ARC, Can anyone help me to sorted out?
public bool ControlAttachment(AttachmentFile file)
{
try
{
if (file != null && file.File != null)
{
string xlsfile = file.File;
string [] xls = {"application/excel","application/vnd.msexcel","xls","xlsx","application/vnd.ms-excel",};
if (xls.ToList().Contains(file.FileType.Trim()))
{
file.FileType = ".xls";
byte[] contents = Convert.FromBase64String(xlsfile);
string LogFilePaths = ConfigurationManager.AppSettings["ExcelMapperPath"];
string fileName = file.FileName.Split('.')[0] + file.FileType;
string LogFile = HttpContext.Current.Server.MapPath(LogFilePaths + file.FileName.Split('.')[0] + file.FileType);
System.IO.File.WriteAllBytes(LogFile, contents);
if (!File.Exists(LogFile))
{
File.Create(LogFile).Dispose();
}
MemoryStream ms = new MemoryStream();
using (var fs = new FileStream(LogFile, FileMode.Open, FileAccess.Write))
{
ms.CopyTo(fs);
ms.Dispose();
}
}
}
return true;
}
catch
{
return false;
}
}