When I Upload a file and after that click on Direct Azure Path it took me to (Redirect) sign in Page
string fileData = request.DocumentData.Split(',')[1];
string fileExtention = GetFileExtension.GetBase64FileExtension(fileData);
byte[] bytes = Convert.FromBase64String(fileData);
string folderName = "PracticeDocuments";
string fileName = "PracticeDoc";
string folderpath = Path.GetFullPath("~/UploadedFiles/" + folderName).Replace("~\\", "");
if (!Directory.Exists(folderpath))
{
Directory.CreateDirectory(folderpath);
}
string filePath = "/UploadedFiles/PracticeDocuments/" + fileName + request.PracticeId.ToString() + "-" + DateTime.Now.Ticks + "." + fileExtention;
string fullpath = Path.GetFullPath("~" + filePath).Replace("~\\", "");
using (FileStream fs = File.Create(fullpath, 1024))
{
fs.Write(bytes, 0, bytes.Length);
}
PracticeDoc practiceDocObj = new PracticeDoc
{
DocumentName = practicedata.FirstName + ' ' + practicedata.LastName + '-' + request.PracticeId.ToString(),
CreatedDate = DateTime.Now,
Description = request.Description,
PracticeId = request.PracticeId,
DocumentData = bytes,
DocumnetPath = "https://testapi.scm.azurewebsites.net/dev/api/files/wwwroot/" + filePath,
};
_practiceDocsRepository.Add(practiceDocObj);
await _practiceDocsRepository.SaveChangesAsync();
Related
I can't access photos to view after uploade.
This is the uploade code
`
public async Task<string> Upload_Image(FormFile file,string name)
{
var newFileName = string.Empty;
if (file.Length > 0)
{
var fileName = string.Empty;
string PathDB = string.Empty;
//Getting FileName
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var FileExtension = Path.GetExtension(fileName);
// concating FileName + FileExtension
newFileName = myUniqueFileName + FileExtension;
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
_env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), name);
}
// Combines two strings into a path.
fileName = _env.WebRootPath + '\\' + newFileName;
// if you want to store path of folder in database
PathDB = name+"/" + newFileName;
newFileName = PathDB;
using (FileStream fs = System.IO.File.Create(fileName))
{
await file.CopyToAsync(fs);
fs.Flush();
}
}
return newFileName;
}`
I am using ID as argument for parameter 'name'.
When I am trying to access the photo using "/ID/whatEverhere.jpg"
return NOTFOUND ??????
You are storing your file in :
fileName = _env.WebRootPath + '\\' + newFileName;`
...
using (FileStream fs = System.IO.File.Create(fileName))
And you return :
PathDB = name+"/" + newFileName;
newFileName = PathDB;
...
return newFileName;
So, that isn't the same path, there isn't your ID in the path you store the file !
I sujest you should cleanup your code.
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 am using Reportviewer in asp.net mvc and rendering it as a pdf format after converting it into byte.
The code is given below:
public ActionResult PrintPO(string type)
{
LocalReport lr = new LocalReport();
string path = Url.Content(Server.MapPath("~/Report/RepPurchaseOrder.rdlc"));
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return Content("Report File Not Found!");
}
ReportDataSource rd = new ReportDataSource("Data", list));
lr.DataSources.Add(rd);
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>10in</PageWidth>" +
" <PageHeight>10in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
FileContentResult fileResult = File(renderedBytes, mimeType);
return fileResult;
}
I want to save this file to my server location. For example: /Content/PDF/Result1.pdf
I want to make a copy of rendered bytes into file so that I can see preview of it later also.
How can I achieve it? I am not using html FileUpload control.
Please help me.
Thanks.
You can save it using FileStream in server-side.
using (FileStream fileStream = System.IO.File.Create(filePath, renderedBytes.Length)){
fileStream.Write(renderedBytes, 0, renderedBytes.Length);
}
I've added the code to save file in specified file path(/Content/PDF/Result1.pdf) at the end of the method before setting FileContentResult
public ActionResult PrintPO(string type)
{
LocalReport lr = new LocalReport();
string path = Url.Content(Server.MapPath("~/Report/RepPurchaseOrder.rdlc"));
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return Content("Report File Not Found!");
}
ReportDataSource rd = new ReportDataSource("Data", list));
lr.DataSources.Add(rd);
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string id="Dynamic ID Will Be Here";
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>10in</PageWidth>" +
" <PageHeight>10in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Saving renderedBytes to File ~/Content/PDF/Result1.pdf
var filesDir = Server.MapPath(#"~/Content/PDF");
if (!Directory.Exists(filesDir)) {
Directory.CreateDirectory(filesDir);
}
var filePath = Path.Combine(filesDir, "Result1.pdf");
using (FileStream fileStream = System.IO.File.Create(filePath, renderedBytes.Length)) {
fileStream.Write(renderedBytes, 0, renderedBytes.Length);
}
FileContentResult fileResult = File(renderedBytes, mimeType);
return fileResult;
}
This question already has an answer here:
ASP.NET + C# HttpContext.Current.Session is null (Inside WebService)
(1 answer)
Closed 9 years ago.
I have an web service.And i am using some session variables in that service.
Code:
[WebMethod(EnableSession = true)]
public static string UploadFiles_Local(Dictionary<int, string> accFile)
{
string FilePath = "";
Dictionary<int, string> dicStatus = new Dictionary<int, string>();
Dictionary<int, string> dicUpload = new Dictionary<int, string>();
System.Web.HttpContext.Current.Session["uLocal"] = System.Web.HttpContext.Current.Server.MapPath("UplodedFiles") + "\\" + DateTime.Now.Ticks.ToString();
foreach (var f_l in accFile)
{
FilePath = f_l.Value;
string fName = FilePath.Substring(FilePath.LastIndexOf("\\") + 1, FilePath.Length - FilePath.LastIndexOf("\\") + 1);
//File reading
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
//Directory Existens checking
if (!Directory.Exists(System.Web.HttpContext.Current.Session["uLocal"].ToString()))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Session["uLocal"].ToString());
}
try
{
//Upload files
long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
string uploadFileName = new FileInfo(FilePath).Name; // File name
Byte[] buffer = new Byte[FileSize];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
fs = null;
fs = File.Open(System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName, FileMode.OpenOrCreate);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buffer);
bw.Close();
dicStatus.Add(f_l.Key, "File " + fName + ". Successfuly uploded to:" + System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName);
dicUpload.Add(f_l.Key, System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName);
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
dicStatus.Add(f_l.Key, "File " + fName + ". Error in uploding to:" + System.Web.HttpContext.Current.Session["uLocal"].ToString() + "\\" + fName + "\r\nError :" + ex.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
if (dicUpload.Count > 0)
{
//Making rar of uploded files
ClsClass.RarFilesT(System.Web.HttpContext.Current.Session["uLocal"].ToString() + ".rar", dicUpload);
FilePath = System.Web.HttpContext.Current.Session["uLocal"].ToString() + ".rar";
}
else
{
FilePath = "Error";
}
return FilePath;
}
I have already enabled session in that web service but stile i get error message :-
Error message:-
'System.Web.HttpContext.Current' is null
And one more ting i need to call this service from globle.ashx file.
Maybe this can help:
http://www.codeproject.com/Articles/35119/Using-Session-State-in-a-Web-Service
But let me tell you that a Web Service should not stored any session states, that is just wrong.
I am developing wpf application. I am using sharpziplib to compress and decompress files. I am easily decompress the .zip files using following code
public static void UnZip(string SrcFile, string DstFile, string safeFileName, int bufferSize)
{
//ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
string rootDirectory = string.Empty;
if (safeFileName.Contains(".zip"))
{
rootDirectory = safeFileName.Replace(".zip", string.Empty);
}
else
{
rootDirectory = safeFileName;
}
Directory.CreateDirectory(App.ApplicationPath + rootDirectory);
while (true)
{
ZipEntry entry = zipInStream.GetNextEntry();
if (entry == null)
break;
if (entry.Name.Contains("/"))
{
string[] folders = entry.Name.Split('/');
string lastElement = folders[folders.Length - 1];
var folderList = new List<string>(folders);
folderList.RemoveAt(folders.Length - 1);
folders = folderList.ToArray();
string folderPath = "";
foreach (string str in folders)
{
folderPath = folderPath + "/" + str;
if (!Directory.Exists(App.ApplicationPath + rootDirectory + "/" + folderPath))
{
Directory.CreateDirectory(App.ApplicationPath + rootDirectory + "/" + folderPath);
}
}
if (!string.IsNullOrEmpty(lastElement))
{
folderPath = folderPath + "/" + lastElement;
WriteToFile(DstFile + rootDirectory + #"\" + folderPath, bufferSize, zipInStream, rootDirectory, entry);
}
}
else
{
WriteToFile(DstFile + rootDirectory + #"\" + entry.Name, bufferSize, zipInStream, rootDirectory, entry);
}
}
zipInStream.Close();
fileStreamIn.Close();
}
private static void WriteToFile(string DstFile, int bufferSize, ZipInputStream zipInStream, string rootDirectory, ZipEntry entry)
{
FileStream fileStreamOut = new FileStream(DstFile, FileMode.OpenOrCreate, FileAccess.Write);
int size;
byte[] buffer = new byte[bufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Close();
}
But the same code is not working with .bz2 files. It is giving error at line
ZipEntry entry = zipInStream.GetNextEntry();
The error is - Wrong Local header signature: 0x26594131. How should I decompress the .bz2 file ? Can you please provide me any code or link through which I can resolve the above issue ?
While you use a ZipInputStream for .zip files, you should use a BZip2InputStream for .bz2 files (and GZipInputStream for .gz files etc.).
Unlike Zip (and RAR and tar), bz2 and gzip are just byte stream compressors. They have no concept of a container format like the aforementioned, and hence why it fails on GetNextEntry. (In other words, bz2 and gzip will only have 1 entry at most).