I want to do this with c# asp.net, can you tell me the actual methods I need to use to handle this part: {get file from filesystem}?
ActionResult FunctionToServeFile(fileName, guid)
{
File result;
var itemEntry = db.items.firstOrDefault(x => x.guid == guid);
var itemPermissionsEntry = itemEntry.userPermissions
.firstOrDefault(x => x.user == user.identity.name);
if(itemPermissionsEntry.view == true || itemPermissionsEntry.Modify == true)
{
result = {get file from filesystem}
return result;
}
else
{
return error;
}
}
There is direct support for this with FileResult, and Controller has a set of helpers:
In your action:
return File(filename, contentType);
This is the solution I arrived at:
public ActionResult DownloadFile(string fileName, Guid guid)
{
Item item = db.Items.FirstOrDefault(x => x.ItemGUID == guid);
if (item == null)
return null;
List <SecurityMask> accessList = GetAccessRightsForItem(item.item_id,
ActiveDirectory.GetUserSID(User.Identity.Name));
bool hasAccess = false || (accessList.Contains(SecurityMask.View) || accessList.Contains(SecurityMask.Modify));
string filePath = Path.GetFullPath(Path.Combine(HttpRuntime.AppDomainAppPath,
"Files\\Items", guid.ToString(), fileName));
string mimeType = MimeMapping.GetMimeMapping(filePath);
bool fileExists = System.IO.File.Exists(filePath);
if (hasAccess && fileExists)
{
return File(System.IO.File.ReadAllBytes(filePath), mimeType);
}
return null;
}
You have to have the file somewhere in your server, so just make a method to get that path and serve it through the controller like this :
string thefile = SomeModelClass.SomeMethod(fileName, guid); // get full path to the file
var cd = new System.Net.Mime.ContentDisposition
{
FileName = Path.GetFileName(thefile),
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
string fileext = Path.GetExtension(thefile);
string mimeType = SomeMetodToMapextensionToMimeType(fileext); // You have to implement this by yourself
return File(System.IO.File.ReadAllBytes(thefile), mime);
Related
I am trying to put a list of file paths into a zip file and download them in my controller but nothing is happening. I haven't gotten any errors and nothing pops up as downloaded after executing the program.
Controller:
[HttpPost]
public ActionResult ExportFile(ClientStatement_Inventory model, string[] years, string[] months, string[] radio, string[] emails, string acctNum)
{
List<string> allPaths = new List<string>();
// Is Account Number empty or Radio not selected
if (String.IsNullOrEmpty(acctNum.Trim()) && radio == null)
{
return Json(new { success = false, message = "* Please Enter Account Number\n\n * Please choose whether to download or email statements" });
}
if (acctNum == "")
{
return Json(new { success = false, message = "* Please Enter Account Number" });
}
else if (radio == null)
{
return Json(new { success = false, message = "* Please Choose whether To Download or Email" });
}
//try
//{
// If months and years are selected
if (months != null)
{
if (years != null)
{
using (var db = new DB())
{
// Get Specific years and months
allPaths = db.ClientStatement_Inventory
.Where(x => x.accountNum == acctNum && years.Contains(x.statementYear) && months.Contains(x.statementMonth))
.Select(c => c.statementPath).ToList();
}
if (allPaths.Count == 0)
{
return Json(new { success = false, message = $"* There were no documents for Account#: {acctNum}" });
}
}
//return View();
}
//Downloading Statements is chosen
if (radio[0] == "Download Statements")
{
foreach (var path in allPaths)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
var result = fileBytes;
string filename = Path.GetFileName("sjdfk.pdf");
string realpath = Server.MapPath("~/Downloads");
string fullPath = Path.Combine(realpath, filename);
string contentType = "application/zip";
string file = builder.ToString();
return File(fullPath, contentType, "Helo");
}
}
//}
//catch (Exception ex)
//{
// //error
// return Redirect("Home/Index");
//}
return Redirect("Home/Index");
}
}
}
If you see my comment //Downloading statement is chosen. Thats where I am trying to download the files. I know my foreach loop is very wrong but nothing is happening I can't even get and error or one file to download.
Also my allPaths variable is an array of multiple strings of the server path name of the files. so they would look like \ipt-siru1\filename
I just don't know what else to try. I've tried so many different things today and still can't get this figured out.
I haven't tested this but you could try something like this to save it into the memorystream:
var downloadFileName = string.Format("YourDownload-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + downloadFileName);
using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
{
zipFile.AddDirectoryByName("Files");
foreach (var path in allPaths)
{
zipFile.AddFile(path);
}
//zipFile.Save(Response.OutputStream);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = downloadFileName,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var memStream = new MemoryStream();
zipFile.Save(memStream);
memStream.Position = 0; // Else it will try to read starting at the end
return File(memStream, "application/octet-stream");
//Response.Close();
}
I am facing this error:
Cannot implicitly convert type 'Model.RouteListModel' to 'string'
ReportModel class:
public class RouteGroup
{
public IGrouping<string, RouteImportModel> Data { get; set; }
}
public class RouteImportModel
{
..
..
}
public class RouteListModel
{
..
..
}
The Service class has the following method which saves data imported from the excel file into various tables of the database:
public RouteListModel GetRouteSaveObj(RouteGroup model, User userInfo)
{
var temp = model.Data.ToList();
var areaTemp = temp.Select(x => x.AREA).Distinct().ToList();
var AreaQuery = $"SELECT AREA_CODE FROM DIST_AREA_MASTER WHERE UPPER(AREA_NAME) IN (UPPER(TRIM('{String.Join("')),UPPER(TRIM('", areaTemp)}')))";
var result = new RouteListModel
{
ROUTE_NAME = temp[0].ROUTE_NAME,
ROUTE_TYPE = temp[0].ROUTE_TYPE,
AREA_CODE = _objectEntity.SqlQuery<string>(AreaQuery).ToList()
};
var entities = new List<RouteEntityModel>();
var sn = 1;
foreach (var item in temp)
{
var query = "";
if (item.ENTITY_TYPE == "D")
query = $"SELECT TO_CHAR(CUSTOMER_CODE) FROM SA_CUSTOMER_SETUP WHERE CUSTOMER_EDESC = '{item.ENTITY}' AND COMPANY_CODE='{userInfo.company_code}' AND DELETED_FLAG='N'";
if (item.ENTITY_TYPE == "R")
query = $"SELECT TO_CHAR(RESELLER_CODE) FROM DIST_RESELLER_MASTER WHERE RESELLER_NAME = '{item.ENTITY}' AND COMPANY_CODE='{userInfo.company_code}' AND DELETED_FLAG='N'";
if (item.ENTITY_TYPE == "P")
query = $"";
if (item.ENTITY_TYPE == "H")
query = $"SELECT TO_CHAR(CODE) FROM BRD_OTHER_ENTITY WHERE DESCRIPTION = '{item.ENTITY}' AND COMPANY_CODE = '{userInfo.company_code}' AND DELETED_FLAG = 'N'";
entities.Add(new RouteEntityModel
{
ENTITY_Code = _objectEntity.SqlQuery<string>(query).FirstOrDefault(),
ENTITY_TYPE = item.ENTITY_TYPE,
ORDER_NO = sn.ToString()
});
sn++;
}
result.RouteEntityModel = entities;
return result;
}
Finally the controller has following method which imports the excel file and binds the data with model
public JsonResult ImportRouteData(HttpPostedFileBase file)
{
Excel.Application application = new Excel.Application();
try
{
if (file == null || file.ContentLength == 0)
{
return Json(new { TYPE = "error", MESSAGE = "Empty File" }, JsonRequestBehavior.AllowGet);
}
else
{
if (file.FileName.EndsWith("xls") || file.FileName.EndsWith("xlsx"))
{
string paths = Server.MapPath("~/DistributionExcel/Branding/" + file.FileName);
string strMappath = "~/DistributionExcel/Branding/";
string path = System.IO.Path.Combine(Server.MapPath(strMappath), file.FileName);
if (!Directory.Exists(strMappath))
{
Directory.CreateDirectory(Server.MapPath(strMappath));
}
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
file.SaveAs(path);
string sheetName = "Sheet 1";
string filepath = paths;
var excel = new ExcelQueryFactory(filepath);
var worksheetNames = excel.GetWorksheetNames();
if (worksheetNames.ElementAt(0) != sheetName)
{
return Json(new { TYPE = "warning", MESSAGE = "Sheet name mismatched" }, JsonRequestBehavior.AllowGet);
}
var listItems = (from a in excel.Worksheet<RouteImportModel>(sheetName)
where !String.IsNullOrEmpty(a.ROUTE_NAME)
select a).ToList();
var groupedData = listItems.GroupBy(x => x.ROUTE_NAME);
var result = string.Empty;
var inserted = 0;
foreach (var item in groupedData)
{
var group = new RouteGroup
{
Data = item
};
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result == "success")
inserted++;
}
return Json(new { TYPE = "success", MESSAGE = inserted + " items successfully inserted" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { TYPE = "error", MESSAGE = "File format error" }, JsonRequestBehavior.AllowGet);
}
}
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
finally
{
application.Quit();
}
}
The problem is in the line below.
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);
if (result == "success") //THIS LINE IS THE PROBLEM
inserted++;
GetRouteSaveObj return object of type RouteListModel so that compare it to string "success" causing the compiler to try to convert result to string implicitly
I don't know how do you determine if it fails or success so this all I could help.
That's because your are trying to compare RouteListModel with success.Have a look at return type of service method GetRouteSaveObj .
As per your service method ,you should check for null instead of comparing it with string.
Simply convert your following code
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result == "success")
inserted++;
to
result = _service.GetRouteSaveObj(group, _workContext.CurrentUserinformation);***ERROR IN THIS LINE AS CANNOT IMPLICITLY CONVERT TYPE ROUTELISTMODEL TO STRING***
if (result!=null)
inserted++;
I have an web API that stores pictures in DB. We store the pictures web address link or in base64 format. Now when we returns the image, and the image is linked in for example in facebbok post, we got the error:
RuntimeBinderException: Operator '==' cannot be applied to operands of type 'GiftUWish.Model.ViewModels.GiftPicture' and 'System.Type'
Here is my code
[HttpGet]
[Route("{giftId}/picture")]
[AllowAnonymous]
public IActionResult GetCustomGiftImage(int giftId)
{
ResponseMessage<dynamic> response = _giftService.GetCustomGiftImage(giftId);
if (response.StatusCode && response.ResultObject != null && response.ResultObject == typeof(GiftPicture))
{
FileContentResult file = new FileContentResult(response.ResultObject.Content, response.ResultObject.MimeType);
return file;
}
else if(response.ResultObject == typeof(string))
{
return string.IsNullOrEmpty(response.ResultObject) ? string.Empty : response.ResultObject;
}
return BadRequest();
}
public ResponseMessage<dynamic> GetCustomGiftImage(int giftId)
{
ResponseMessage<dynamic> response = new ResponseMessage<dynamic>();
try
{
GiftEntity gift = _repository.FindByID(giftId);
if (!string.IsNullOrEmpty(gift.Image) && gift.Image.StartsWith("data:"))
{
GiftPicture giftPicture = CreateGiftPicture(gift.Image);
response.ResultObject = giftPicture;
}
if (!string.IsNullOrEmpty(gift.Image) && gift.Image.StartsWith("http"))
{
response.StatusCode = true;
response.ResultObject = gift.Image;
}
return response;
}
catch (Exception ex)
{
response.StatusCode = false;
response.ErrorMessage = SetErrorMessage(ex);
response.ResultObject = new GiftPicture();
return response;
}
}
private GiftPicture CreateGiftPicture(string dataUri)
{
string[] dataUriMetaAndContent = dataUri.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string dataUriMeta = dataUriMetaAndContent[0];
string dataUriContent = dataUriMetaAndContent[1];
string mimeType = dataUriMeta.Replace("data:", "").Split(';')[0];
return new GiftPicture(mimeType, dataUriContent.Base64DecodeToBytes());
}
I think the error is here:
response.ResultObject == typeof(GiftPicture))
You are trying to compare a GiftPicture instance to a type - if you want to check to see if ResultObject is an instance of GiftPicture then try the following:
response.ResultObject is GiftPicture
(You should also do the same where you check against typeof(string))
Please see the below code where List<order> metadata contains values for my SharePoint columns/fields. I have to validate against Field.validationformula specified in SharePoint site. Can some one helps me to elaborate the provision how to do this validation.
public bool UploadDocumentwithMetadata(string fileName, string filePath, string docLibraryName, bool overwrite,
List<Order> metadata, string subfoldername)
{
bool uploadStatus = false;
string fileurl;
try
{
// Create the new file
if (subfoldername == "")
fileurl = fileName;
else
fileurl = Path.Combine(docLibraryName + "/" + subfoldername, fileName);
var newFile = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(filePath),
Url = fileurl,
Overwrite = overwrite
};
Microsoft.SharePoint.Client.ListItem item = null;
var docs = _site.Lists.GetByTitle(docLibraryName);
if (docs != null)
{
StringBuilder SB = new StringBuilder();
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
uploadStatus = true;
item = uploadFile.ListItemAllFields;field.Value.ToString();
foreach (var order in metadata)
{
Field fld = null;
foreach (var eachfield in docs.Fields)
{
if (eachfield.InternalName == order._InternalName)
{
fld = eachfield;
break;
}
}
string validationformula = fld.ValidationFormula;
item[order._InternalName] = order._Range;
}
/////
****/
//if columns satisfies fld.ValidationFormula;
//then upload
//else exist
/***
/////
}
return uploadStatus;
}
I'am trying create some validation for file size. My code:
[HttpPost]
public ActionResult Index(FotoModel model)
{
TryUpdateModel(model);
if (ModelState.IsValid)
{
if (model != null && model.File != null)
{
var fileName = Path.GetFileName(model.File.FileName);
var fileExtension = Path.GetExtension(fileName);
long fileSize = new FileInfo(fileName).Length;
fileName = "file" + fileExtension;
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
if (fileSize < 55000)
{
model.File.SaveAs(path);
model.link = fileName.ToString();
}
else
{
ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
}
return View(model);
}
}
return View(model);
}
And in this line:
long fileSize = new FileInfo(fileName).Length;
I'am receiving error: "File cannot be found". Do You know how can I resolved this ?
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; // <---Your file Size or Length
.............
.............
}
}
What you are looking is a ContentLength
public ActionResult Index(FotoModel model)
{
if (model != null && model.File != null)
{
var fileSize = model.File.ContentLength;
}
}