I am working on an ASP .net webpage which receives a form which is posted to it. The posted form has three as well.
filename = uploadFile(HttpContext.Current.Request.Files["file1"], path);
This is the code through which i upload a file to my server. And this is the code of the function.
public string uploadFile(HttpPostedFile file, string dest)
{
string filename = file.FileName;
string path = Server.MapPath(dest);
String extension = Path.GetExtension(file.FileName);
filename = filename.Replace(extension, "");
filename = filename.Replace(".", "");
filename = System.DateTime.Now.ToString("ddMMyyyyhhmmss") + filename + extension;
string savepath = path + "/" + filename;
file.SaveAs(savepath);
return filename;
}
The problem is I am not able to check if file1 from the posted form actually has file. Is it possible?
Use the FileUpload control in conjunction with the HasFile property:
FileUpload.HasFile Property
If you have to do it that way, you can simply check if the ContentLength is greater than zero.
Related
I am using the System.Net.WebClient.DownloadStringTaskAsync async method to upload a web page content and process it or just save it on my local folder. Everything is fine but when the web page contains some special characters like ™ or ®, they are not getting downloaded. Am I missing something here?
String contentToScrapeURL = "https://www.naylornetwork.com/aaho-advertorial/newsletter.asp?issueID=89542";
Boolean success = true;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
Found it, or remembered it.
I did set the System.Net.WebClient.Encoding to Encoding.UTF8
So this below is the updated code
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Encoding = Encoding.UTF8;
String pageSourceCode = await wc.DownloadStringTaskAsync(contentToScrapeURL);
String path = #"C:\MyProjects\TestingThings\App_Data\" + "test.html";
File.WriteAllText(path, pageSourceCode);
}
My objective is User can choose an image from any place from their desktop and upload/tweet the same to twitter. I'm struggling to set the relative path to the imagePath variable.
The path (D Drive) were my image stored. While running the application it looks in different path. This throws an error System.IO.FileNotFoundException. I tried Server.MapPath too. Assist me to resolve it.
Solved the issue as following
string filePath; string imagePath = "";
if (imgFile == null)
{
imgFile = Request.Files["imgFile"];
}
if (imgFile.FileName != "")
{
filePath = Server.MapPath("~/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath = filePath + Path.GetFileName(imgFile.FileName);
imgFile.SaveAs(filePath);
imagePath = Path.Combine(Server.MapPath(#"~/Images/"), filePath);
}
File must be saved in the server location, try to replace the below instruction:
string imagePath=Path.Combine(Request.MapPath("~/"),fileName);
with the below instruction
var fileName = Path.GetFileName(file.FileName);
var imagePath = Path.Combine(Request.MapPath("~/"), fileName);
file.SaveAs(imagePath);
........
Cordially
Am running the project on the visual studio 2015, When I tried to read the PDF its giving me the following error;
Access to the path 'E:\FILE\FILEUPLOAD\InnerFile\File' is denied.
Function Defination
var cd = new System.Net.Mime.ContentDisposition { FileName = "PDF.pdf", Inline = true };
string contentType = MimeMapping.GetMimeMapping("PDF.pdf");
Response.AppendHeader("Content-Disposition", cd.ToString());
var innerPath = "InnerFile/File" ;
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
return File(bytes, contentType);
NOTE:
Given Full permission to user
Physically File Exists
I dont understand what to do now please help!
Your FileInfo instance indeed references 'E:\FILE\FILEUPLOAD\InnerFile\File\PDF.pdf':
FileInfo fi = new FileInfo(PDFUploadRootPath + innerPath + "/PDF.pdf");
but when trying to read the file contents you forgot the file name and only use the path 'E:\FILE\FILEUPLOAD\InnerFile\File':
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath);
Thus, also add the file name for reading all file bytes:
byte[] bytes = System.IO.File.ReadAllBytes(PDFUploadRootPath + innerPath + "/PDF.pdf");
Furthermore, as others have mentioned in comments, you should really use Path.Combine to glue path parts together, not simple string concatenation...
Try using FileStream instead of byte array for reading the pdf file.
FileStream templateFileStream = File.OpenRead(filePath);
return templateFileStream;
Also check (through code) if user has write permission to directory or path:
public static bool HasUserWritePermission(String path, String NtAccountName)
{
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
Boolean hasPermission = false;
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
{
//Cast to a FileSystemAccessRule to check for access rights
if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
{
hasPermission = true;
}
else
{
hasPermission = false;
}
}
}
return hasPermission;
}
I'm trying to read the video name in servlet, if the video name is in english i can read it fine, if the video name is in arabic i couldn't read it as expected
if (!item.isFormField()) {
String value = (String) item.getName();
String videoName = new String(
value.getBytes("iso-8859-1"), "UTF-8");
if (videoName != "")
item.write(new File(UPLOAD_DIRECTORY
+ videoName));
arrayList.add(videoName);
however is working if the item is not form field
else if (item.isFormField()) {
String inputName = (String) item.getFieldName();
String value = (String) item.getString();
value = new String(
value.getBytes("iso-8859-1"), "UTF-8");
hashMap.put(inputName, value);
}
I have solved the problem by adding req.setCharacterEncoding("UTF-8");
I Want to download the files present in the Folder i.e App_Data.This file I have saved with GUID but not able to download.
My code is as follows:
public FilePathResult DownLoadDispatch(long CIDInvID)
{
var Attr = db.ConsolidatedInvoiceDispatchDocuments.FirstOrDefault(x => x.ConsolidatedInvoiceDispatchID == CIDInvID);
string path = System.Web.HttpContext.Current.Server.MapPath("~") + "/App_Data/files/Dispatch/" + Attr.StoredName.ToString();
string fileName = Attr.FileName;
return File(path + fileName, "text/plain", "test.txt");
}