I have an application that uploads images, I am trying to get the path to store on the server and not on my C:drive. Below is the code in the controller:
if (ModelState.IsValid)
{
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/");
try
{
if (!Directory.Exists(physicalPath))
Directory.CreateDirectory(physicalPath);
string physicalFullPath = Path.Combine(physicalPath, ImageName);
file.SaveAs(physicalFullPath);
customer.CustomerLogo = ImageName;
customer.CustomerLogoPath = physicalFullPath;
db.Customers.Add(customer);
db.SaveChanges();
}
catch(Exception e)
{
return View("Error",e.Message );
}
}
return RedirectToAction("Index");
}
return View(customer);
}
It's currently being stored like this(See above Image) I need the path to be "admin.loyaltyworx.co.za\Images\jeep.jpg" How can I achieve this?
Use
string physicalPath = "c:\\admin.loyaltyworx.co.za\\Images";
Instead of
string physicalPath = Server.MapPath("~/Images/");
Related
I'm now getting a file from specific drive on SharePoint,but the customer asked to search for the file without specifying a drive.
public static byte[] SharePointDownload(string token, string fileName, string sharepointTargetLibrary)
{
string baseSiteId = GetSiteId(token);
string folderId;
if (string.IsNullOrEmpty(baseSiteId))
{
return null;
}
else
{
folderId = GetFolderId(token, baseSiteId, sharepointTargetLibrary);
if (string.IsNullOrEmpty(folderId))
{
return null;
}
}
try
{
WebClient wc = new WebClient();
byte[] result;
wc.Headers[HttpRequestHeader.Authorization] = "Bearer " + token;
wc.Headers[HttpRequestHeader.Accept] = "application/json";
result = wc.DownloadData(string.Format(#"https://graph.microsoft.com/v1.0/sites/{0}/drives/{1}/root:/{2}:/content", baseSiteId, folderId, fileName));
wc.Dispose();
if (result.Length>0)
{
return result;
}
else
{
return null;
}
}
catch (Exception ex)
{
LoggerHelper.Log(ex.Message);
return null;
}
}
now i want to know if this line
result=wc.DownloadData(string.Format(#"https://graph.microsoft.com/v1.0/sites/{0}/drives/{1}/root:/{2}:/content", baseSiteId, folderId, fileName));
can get rid of folderId and searches with the fileName only specified
Using Microsoft Graph, you search a drive
GET /sites/{site-id}/drive/root/search(q='{search-text}')
THIS IS MY FILE UPLOAD AND DOWNLOAD CODE
[HttpPost]
public ActionResult Save(Rent Rent , FileUpload upload, HttpPostedFileBase file)
{
if (Rent.Id == 0)
_Context.Rent.Add(Rent);
else
{
var rentInDb = _Context.Rent.Single(c => c.Id == Rent.Id);
rentInDb.tenantId = Rent.tenantId;
rentInDb.unitId = Rent.unitId;
rentInDb.startDate = Rent.startDate;
rentInDb.endDate = Rent.endDate;
rentInDb.Amount = Rent.Amount;
rentInDb.leaseStatus = Rent.leaseStatus;
}
_Context.SaveChanges();
var rent = _Context.Rent.Single(r => r.Id == Rent.Id);
var up = Request.Files["file"];
if (up.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/uploads"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "~/uploads/" + newpath;
upload.length = imagepath;
upload.Rent = rent;
_Context.FileUpload.Add(upload);
_Context.SaveChanges();
}
return RedirectToAction("leaseStatus", "Home");
}
public ActionResult Downloads(int id)
{
var fl = _Context.FileUpload.Where(f => f.rentId == id);
var up = Request.Files["file"];
return View(fl );
}
public FileResult Download(string ImageName)
{
var FileVirtualPath = "~/uploads/" + ImageName;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
THIS IS MY VIEW !!
#model IEnumerable<mallform.Models.FileUpload>
#{
ViewBag.Title = "Downloads";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Downloads</h2>
#foreach (var file in Model)
{
Download
}
THIS SHOWS STANDARD 404.0 AND SOMETIME hidden element error :( Please help. In my code it includes the upload a file code,
then there Is a download action which leads me to download view and In download view, I have a link to download the file by file result. But It always shows me an error. Please tell me if there is an issue with the path or what is going on?
Error Code 404 means the url is not found by your anchor tag. https://en.wikipedia.org/wiki/HTTP_404
You need to pass ImageName parameter from your anchor tag to the controller. You can do something like this:
View
#model IEnumerable<mallform.Models.FileUpload>
#{
ViewBag.Title = "Downloads";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Downloads</h2>
#foreach (var file in Model)
{
#Html.ActionLink(
"Download File", // Anchor Text
"Download", // Action Name
"Controller Name", // Controller Name
new {
ImageName= "Pass the value of imagename parameter"
},
null // Html Attributes
)
}
Controller
public FileResult Download(string ImageName)
{
//var FileVirtualPath = "~/uploads/" + ImageName;
//If using Physical Path
//var FileVirtualPath = HttpContext.Current.Request.MapPath("~/uploads/" + ImageName);
//If using Virtual Path
var FileVirtualPath = HttpContext.Current.Server.MapPath("~/uploads/" + ImageName);
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
File Result Action should be like this.
public FileResult Download(string ImageName)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(#"~/uploads/"+ImageName));
string fileName = "myfile."+Path.GetExtension(Server.MapPath(#"~/uploads/"+ImageName));
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Is it possible to return both file for download and update a view from IActionResult?
If not, is there a workaround? (JavaScript or AJAX)
I am hoping to refresh a view after the file download.
Code:
[HttpPost]
public IActionResult ProcessFile(ViewModel model, List<IFormFile> files)
{
var uploadedfileName = UploadFile(files);
try
{
if (uploadedfileName != null)
{
// Generate a report for download
var fileInfo = GenerateReports(model.Host, uploadedfileName);
// Prompt Download File
var webClient = new System.Net.WebClient();
var downloadData = webClient.DownloadData(fileInfo.ToString());
var content = new System.IO.MemoryStream(downloadData);
var contentType = "APPLICATION/octet-stream";
var fileName = Path.GetFileName(fileInfo.ToString());
return File(content, contentType, fileName);
}
else
{
ViewBag.Message = "Please select the file";
}
}
catch (Exception e)
{
// Log Error
}
finally
{
// Delete the file after the report is generated
System.IO.File.Delete(uploadedfileName);
}
return View("Index");
}
I have issue in uploading images path into database and moving imagesg into folder, here is code:
public ActionResult UploadImages(
HttpPostedFileBase formFilled,
HttpPostedFileBase sixPics,
HttpPostedFileBase buyerCNIC,
HttpPostedFileBase sellerCNIC
)
{
if (Session["user"] == null)
{
return RedirectToAction("Login", "User");
}
CustomerDocumentImages dbCustomerDocs = new CustomerDocumentImages();
string recieverName = Request.Form["RecieverName"];
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg"
};
dbCustomerDocs.FormFilledPhysicalPath = formFilled.ToString();
var _formFilled = Path.GetFileName(formFilled.FileName); //getting only file name(a.jpg)
var ext = Path.GetExtension(formFilled.FileName);
if (allowedExtensions.Contains(ext))
{
string name = Path.GetFileNameWithoutExtension(_formFilled); //getting file name without extension
string formImage = name + "_" + DateTime.Now + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Images"), formImage);
dbCustomerDocs.FormFilledPhysicalPath = path;
dbCustomerDocs.FormFilled = _formFilled;
dbCustomerDocs.RecieverName = recieverName;
try
{
var currentAllotmentId = Convert.ToInt32(Request.Form["AllotmentId"]);
var dbAllotment = db.Allotments.SingleOrDefault(i => i.AllotmentId == currentAllotmentId);
dbCustomerDocs.AllotmentId = dbAllotment.AllotmentId;
dbAllotment.IsCustomerDocsUploaded = true;
}
catch (Exception)
{
ModelState.AddModelError("", "Please select valid allotment");
}
db.CustomerDocumentImagess.Add(dbCustomerDocs);
db.SaveChanges();
formFilled.SaveAs("~Images"+path);
return RedirectToAction("Index");
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
I have also used server.mappath but it woking fine on localhost but giving error on windows live server( on save as method ) , in case of combine.mappath works fine but not moving image into folder. please guide me, thanks in advance.
I enable my users to download files, some times the files are archived or do not exist at the location, I currently display a 404, I created a specific error page for this specific scenario but I am unable to display it because I have to return something in the FileDownload Result and I am unable to do a response redirect. Also I tried to return content with javascript but that is also not compatible with FileDownloadResult type. How do I route the user to the intended error page which I have will render from its own controller/action?
public DownloadFileResult Download(string file)
{
try
{
string loadLististFileName = file;
// get the displayed filename, extract the file name
string fileNamePath = loadLististFileName;
string fileName = Path.GetFileName(fileNamePath);
string dirName = Path.GetDirectoryName(fileNamePath);
string dirPath = dirName.Replace("\\", ",");
string[] dir = dirPath.Split(',');
int dirlength = dir.Length;
string year = dir[dirlength - 3];
string month = dir[dirlength - 2];
string day = dir[dirlength - 1];
var fileData = IOHelper.GetFileData(fileName, dirName);
fileName = IOHelper.GetPrimaryFileName(file);
return new DownloadFileResult(fileName, fileData);
}
catch (FileNotFoundException)
{
//return Content("<script language='javascript' type='text/javascript'>alert('Image not found!');</script>");
Response.Redirect("Exception/FileIndex");
}
}
try to return ActionResult instead, something like this:
public ActionResult DownLoadFile(int Id)
{
var model = new PreviewFileAttachmentViewModel(Id, _attachFileProvider);
if (model.FileExist)
return File(model.AbsFileNamePath, model.ContentType, model.FileName);
else
return RedirectToAction("FileNotFound");
}