How Can I click and download Photo In mvc - c#

I have one form when i create on record i can attach some photo for that ,i attach in there photos more than one but i cant click to each one them , to review and download it how can i do that click to each one of them and to view and Download each one my structure in asp.net core is MVC and i use controller and view i share my UI cod and backend code to help me
<div class="col-md-8">
#foreach (var item in #Model.Gallarys)
{
<div class="form-group col-md-4">
<div class="col-md-12 col-sm-12 text-center" style="margin-top:20px;">
<div class="fileinput fileinput-new text-center" data-provides="fileinput">
<div class="fileinput-new thumbnail">
<img src="#(item.Avatar != null ? Config.BannerThumbPicPath + item.Avatar : "/assets/img/image_placeholder.jpg")" alt="...">
</div>
</div>
</div>
</div>
}
</div>
public async Task<BaseResult> CreateGallary(Gallary gallary, IFormFile Pic)
{
gallary.CreateDate = DateTime.Now;
gallary.Avatar = await SavePic(Pic, gallary.BannerId.ToString().GetUrlFriendly() + Pic?.GetExtention());
return base.Create(gallary);
}
public List<Gallary> GetAllPic(int id)
{
return UOW.Gallaries.GetAll().Where(_ => _.BannerId == id).ToList();
}
#region ذخیره تصویر
public async Task<string> SavePic(IFormFile Pic, string FileName)
{
if (Pic != null && Pic.IsImage())
{
string LargePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot" + Config.BannerLargPicPath + FileName);
var i = 1;
string BaseName = FileName;
while (File.Exists(LargePath))
{
FileName = i + "-" + BaseName;
LargePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot" + Config.BannerLargPicPath + FileName);
i++;
}
string ThumbPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot" + Config.BannerThumbPicPath + FileName);
using (var stream1 = new FileStream(LargePath, FileMode.Create))
{
await Pic.CopyToAsync(stream1);
}
using (var stream2 = new FileStream(ThumbPath, FileMode.Create))
{
await Pic.CopyToAsync(stream2);
}
ImageResizer.CropImage(LargePath, LargePath, LargeWidth, LargeHeight, 100);
ImageResizer.CropImage(ThumbPath, ThumbPath, ThumbWidth, ThumbHeight, 100);
return FileName;
}
return null;
}

Related

How to retrieve old Path image when we not update c# mvc

I am working on update form, my scenario is I don't want to update new image I just want to update only other data then submit when I submit the form "image URL" shows the null value not show the old path of the image.i have tried this code which I am sharing you kindly tell me how to resolve this issue.
Just give the hint of code then I will resolve this.
Model
public class ProductViewModel{
public string ImageUrl { get; set; }
[NotMapped]
public HttpPostedFileBase imageUpload { get; set; }
public ProductViewModel()
{
ImageUrl = "~/Scripts/imageloading/image.jpg";
}
}
c#
public ActionResult AddOrEditProducts(ProductViewModel prod)
{
Product pro = new Product();
ProductDetail p_spec = new ProductDetail();
var result = new jsonMessage();
try
{
List<ProductType> PTlist = _IproductType.PTList();
ViewBag.Ptlist = new SelectList(PTlist, "PType_ID", "P_Name");
//Product Color List
List<P_Color> pColorList = _IProductColor.PColorlist();
ViewBag.pColor_List = new SelectList(pColorList, "C_ID", "C_Name_OR_Code");
List<P_Size> pSizeList = _ISize.pSizeList();
ViewBag.pSizeLists = new SelectList(pSizeList, "S_ID", "S_Size");
if (prod.imageUpload != null) // shows null here
{
string filename = Path.GetFileName(prod.imageUpload.FileName);
string _filename = DateTime.Now.ToString("yymmssff") + filename;
string extension = Path.GetExtension(prod.imageUpload.FileName);
prod.ImageUrl= "~/upload/" + _filename;
if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".jpg" || extension.ToLower() == ".png")
{
if (prod.imageUpload.ContentLength <= 1000000)
{
prod.imageUpload.SaveAs(Path.Combine(Server.MapPath("~/upload/"), _filename));
p_spec = new ProductDetail();
p_spec.ProductID = prod.ProductID;
p_spec.OS = prod.OS.Trim();
p_spec.DualSim = prod.DualSim.Trim();
p_spec.Camera = prod.Camera.Trim();
p_spec.TouchScreen = prod.TouchScreen.Trim();
p_spec.ScreenSize = prod.ScreenSize.Trim();
p_spec.ProcessorType = prod.ProcessorType.Trim();
p_spec.RAM = prod.RAM.Trim();
p_spec.InternalMemory = prod.InternalMemory.Trim();
p_spec.Wifi = prod.Wifi.Trim();
p_spec.BatteryLife = prod.BatteryLife.Trim();
p_spec.Other = prod.Other.Trim();
p_spec.PDescription = prod.PDescription.Trim();
p_spec.Model = prod.Model.Trim();
p_spec.Condition = prod.Condition.Trim();
p_spec.Discount = prod.Discount;
p_spec.ImageUrl = prod.ImageUrl;
}
else
ViewBag.sizemsg = "Size Limit accessed ";
}
else
ViewBag.fileformat = "File is not Format is not Correct";
pro = new Product();
pro.ProductID = prod.ProductID;
pro.PName = prod.PName.Trim();
pro.ManificturedPrice = prod.ManificturedPrice;
pro.P_SizeID = prod.P_SizeID;
pro.P_Color_ID = prod.P_Color_ID;
pro.PType_ID = prod.PType_ID;
pro.UnitWeight = prod.UnitWeight;
pro.UnitInStock = prod.UnitInStock;
}
if (prod.ProductID == 0)
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message= "Product has been saved success..";
result.Status = true;
ModelState.Clear();
}
else
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message = "Product Update Successfully";
result.Status = true;
ModelState.Clear();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
}
return RedirectToAction("ProductsList");
}
View
<div id="tabimage" class="tab-pane">
<h3 class="mgtp-15 mgbt-xs-20"> Images</h3>
<div class="vd_panel-menu">
<input type="submit" value="Save Changes" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="btnSave" />
<button type="reset" value="Cancel" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="" />
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-lg-3 file_upload_label"> <span title="" data-toggle="tooltip" class="label-tooltip" data-original-title="Format JPG, GIF, PNG. Filesize 8.00 MB max."> Add a new image to this product </span> </label>
<div class="col-lg-9">
<div class="col-lg-5">
<span class="btn vd_btn vd_bg-green fileinput-button">
<i class="glyphicon glyphicon-plus"></i> <span>Add files...</span>
<input type="file" name="imageUpload" multiple id="imageUpload" onchange="ShowimahePreview(this,document.getElementById('previewImage'))" />
</span>
</div>
<div class="col-lg-4">
<img src="#Url.Content(Model.ImageUrl)" alt="Alternate Text" height="150" weight="" id="previewImage" />
</div>
</div>
</div>
</div>
</div>

MVC passing a file to a controller via $.ajax

I'm trying to achieve to pass a file from the client to my controller in mvc in order to transform the file to a ByteArray, I was thinking that was a simple task but it actually giving me some hard times.. so far I'm able to hit correctly my controller:
HTML
<form method="post" id="myform" enctype="multipart/form-data"
asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<p>Seleziona un file ORI ed un file MOD.</p>
<label for="fileOri">Seleziona ORI</label>
<input id="fileOri" type="file" name="fileOri" multiple />
<p></p>
<label for="fileMod">Seleziona MOD</label>
<input id="fileMod" type="file" name="fileMod" multiple />
<p></p>
<input id="check" name="checkBoxCorreggi" type="checkbox" />
<label for="check">Correggi Checksum</label>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<p></p>
<input type="submit" id="VerificaChecksum" value="Verifica Checksum" />
<!--value= "Verifica Checksum-->
<p></p>
</div>
</div>
</form>
JavaScript
$(function () {
$('#VerificaChecksum').click(function () {
var file = document.getElementById('fileOri'),
formData = new FormData();
if (file.files.length > 0) {
for (var i = 0; i < file.files.length; i++) {
formData.append('file' + i, file.files[i]);
}
}
$.ajax({
url: '#Url.Action("UploadFiles", "UploadFiles")',
type: 'POST',
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false
});
});
});
MVC CONTROLLER
public class UploadFilesController : Controller
{
int result = 0;
int count = 0;
byte[] fileOri;
byte[] fileMod;
[DllImport(#"c:\Windows\System32\inetsrv\dll194.dll", EntryPoint = "get_cks_XXX")]
public static extern int get_cks_XXX(byte[] pBuf_mod, byte[] pBuf_ori, int len_Buf, bool flag);
private readonly IHostingEnvironment _hostingEnvironment;
public UploadFilesController(IHostingEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
#region snippet1
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(IList<IFormFile> files, string[] checkBoxCorreggi)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new MemoryStream())
{
await formFile.CopyToAsync(stream);
if (count == 0)
{
fileOri = stream.ToArray();
}
else
{
fileMod = stream.ToArray();
}
}
}
count++;
}
if (checkBoxCorreggi.Length == 1)
{
result = get_cks_XXX(fileMod, fileOri, fileOri.Length, true);
return File(fileMod, "application/force-download", "modCorretto.mod");
}
else
{
result = get_cks_XXX(fileMod, fileOri, fileOri.Length, false);
return Ok(new { count = files.Count, size, filePath });
}
}
#endregion
}
As I said before I'm currently able to hit my controller, but the problem is that the IList<IFormFile> files is actually null, where I'm getting wrong?
I hope this will work.
I have just only one file to send so i am doing this is Asp.Net Core
You can add your conditions as well like Files.Count or something you want.
Here is my code to save file
[HttpPost]
public async Task<JsonResult> SaveRegistration(string registration)
{
var message = "";
var status = "";
try
{
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Files\\Images");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += "\\";
if (!string.IsNullOrEmpty(registration))
{
var reg = new Registration();
reg.Name = registration;
var file = Request.Form.Files[0];
if (file != null)
{
var fileName = file.FileName;
if (System.IO.File.Exists(path + fileName))
{
fileName = $"{DateTime.Now.ToString("ddMMyyyyHHmmssfff")}-{fileName}";
}
using (var fileStream = new FileStream(path + fileName, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
reg.Picture = fileName;
}
_context.Registration.Add(reg);
await _context.SaveChangesAsync();
message = "Data is not saved";
status = "200";
}
}
catch (Exception ex)
{
message = ex.Message;
status = "500";
}
return Json(new
{
Message = message,
Status = status
});
}

Gives a HTTP404 Error (Azure Storage/Visual Studio)

i am working on a website where you could upload a image onto azure storage as a blob and also to download the blob, however when i download the image it gives me a "this file format cannot be opened" when opening the pic. i was wondering where could i display the fileStream?
heres my javascript:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
#Html.ActionLink("Upload to Azure Blob", "UploadBlob", new { Controller = "blob" }, new { #class = "btn btn-link" })
<div class=" table table-striped table-responsive">
<table id=" tablex">
<thead>
<tr>
<th>Container</th>
<th>Actual FileName</th>
<th> Uri </th>
</tr>
</thead>
<tbody>
#if(Model != null)
{
foreach (var item in Model)
{
<tr id="row_#item.PrimaryUri">
<td>#item.BlockContainerName</td>
<td>#item.ActualFileName</td>
<td>
<a herf=#item.PrimaryUri>#item.PrimaryUri </a>
</td>
#*<td>#Html.ActionLink("Remove", "DeletedBlob", new { controller = "blob", file = #item.FileNameWithoutExt, extension = #item.FileNameWithoutExt })</td> *#
<td><a href='#Url.Action("Download", "DownloadBlob", new { file = #item.FileNameWithoutExt, extension = #item.FileNameWithoutExt })'>Download</a></td>
<td>
<input type="submit" href="#" class="btn btn-link" id="btndel" value="Remove" data-id="#item.ActualFileName" />
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
This is the javascript method ive written in order to download the blob however i've been trying to find out where the problem
In my controller class i have:
public async Task<ActionResult> DownloadBlob(string file, string extension)
{
string downloadPath = await repo.DownloadBlobAsync(file, extension);
return Json(downloadPath);
}
and in my storage class:
public async Task<string> DownloadBlobAsync (string file, string fileExtension)
{
_cloudBlobContainerx = _cloudBlobClientx.GetContainerReference(containerNamex);
CloudBlockBlob blockBlob = _cloudBlobContainerx.GetBlockBlobReference(file + "." + fileExtension);
var path = downloadPath + file + "." + fileExtension;
using (var fileStream = System.IO.File.OpenWrite(path))
{
//fileStream.Position = 1;
//fileStream.Seek(0, SeekOrigin.Begin);
await blockBlob.DownloadToStreamAsync(fileStream);
return path;
}
}
You are using your file name as your extension in your Action;
extension = #item.FileNameWithoutExt
It could explain why get the 404, as the blob probably don't exist with this extension.
We need to use the #Url.Action as following:#Url.Action("actionName","controlName",routeValues).
Gives a HTTP404 Error (Azure Storage/Visual Studio)
It indicates that can't route that path. So you could add the controller named DownloadBlob and add the method Download. We need to make sure that it has the same paramter name are in the routeValues.
public void Download(string file, string extension)
{
var container = cloudBlobClient.GetContainerReference("test");
container.CreateIfNotExists();
var blockBlob = container.GetBlockBlobReference(file + "." + fileExtension);
blockBlob.FetchAttributes();
var contentType = blockBlob.Properties.ContentType;
MemoryStream memStream = new MemoryStream();
blockBlob.DownloadToStream(memStream);
var response = HttpContext.Response;
response.ContentType = contentType;
response.AddHeader("Content-Disposition", "Attachment; filename=" + file + "." + fileExtension);
response.AddHeader("Content-Length", blockBlob.Properties.Length.ToString());
response.BinaryWrite(memStream.ToArray());
}
The following is the test result on my side.

adding photo and model

I am new to asp.net core. I am facing a problem when uploading a file(image) with my model.
the viewmodel :
namespace WebApplication1.ViewModels
{
public class HotelViewModel
{
public String NomHotel { get; set; }
public String NomAgence { get; set; }
public String Filepath{ get; set; }
}
}
this is the cshtml :
#model WebApplication1.ViewModels.HotelViewModel
<form novalidate method="post" enctype="multipart/form-data" asp-
controller="Hotel" asp-action="Hotel">
<div id="parent">
<div id="wide" class="col-lg-4">
<div asp-validation-summary="ModelOnly"></div>
<div class="form-group">
<label asp-for="NomHotel"></label>
<input asp-for="NomHotel" class="form-control" />
<span asp-validation-for="NomHotel"></span>
</div>
<div class="form-group">
<label asp-for="NomAgence"></label>
<input asp-for="NomAgence" class="form-control" />
<span asp-validation-for="NomAgence"></span>
</div>
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple class="btn" />
</div>
<div id="#rest">
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-lg btn-
success ahbat" />
</div>
</div>
</div>
</div>
and this is the controller :
[HttpPost]
public IActionResult Hotel(HotelViewModel mod)
{
Hotel hotel = new Hotel
{
NomAgence = mod.NomAgence,
NomHotel = mod.NomHotel
};
var newFileName = string.Empty;
if (HttpContext.Request.Form.Files != null)
{
var fileName = string.Empty;
string PathDB = string.Empty;
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
//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;
// Combines two strings into a path.
fileName = Path.Combine(_environment.WebRootPath, "HotelImg") + $#"\{newFileName}";
// if you want to store path of folder in database
PathDB = "demoImages/" + newFileName;
hotel.Piscine = newFileName;
using (FileStream fs = System.IO.File.Create(fileName))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
}
IH.Create(hotel);
return View();
}
as said I have tried different combinations of code but I always get the file or the model never both and I need both of them. This is the most correct code I can show you sorry if it is not too clear.

Asp.NET MVC 4 Ajax Request Cancels on Submit

Issue Is with Ajax Request Cancel
After i call the ProcessMessage from form submit i am having issue
Issue with submitting your page is canceling my ajax request, so I am getting error..
Please help me on this
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
<div>
<b>Upload File</b>
<input type="file" name="file" />
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus();"/><br />
</div>
<div>
#ViewBag.Message
</div>
<div style="width: 30%; margin: 0 auto;">
<div id="progressbar" style="width: 300px; height: 15px"></div>
<br/>
</div>
}
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function progressStatus() {
var oReq = new XMLHttpRequest();
oReq.open("get", "/Home/ProcessMessage", true);
oReq.send();
setInterval(showResult, 1000);
function showResult() {
var result = "";
if (result !== oReq.responseText) {
result = oReq.responseText;
debugger;
$("#progressbar").html(result);
}
}
return false;
}
</script>
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
var fname = Path.GetFileName(file.FileName);
var exis = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Storage/uploads"), fname);
if (System.IO.File.Exists(exis))
{
ViewData["Message"] = "The file " + fname + " has already exists";
}
else
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var folderPath = Server.MapPath("~/Storage/uploads");
fname = fileName;
var path = Path.Combine(folderPath, fileName);
var filebytes = new byte[file.ContentLength];
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
file.SaveAs(path);
}
ViewData["Message"] = "The file " + fname + " has uploaded successully";
}
catch (Exception e)
{
ViewData["Message"] = "The file " + fname + " Could not upload";
ViewData["Message"] = e.Message;
}
}
}
else
ViewData["Message"] = "Please choose file";
return View();
}
public class ProgressiveResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
for (int i = 0; i < 20; i++)
{
context.HttpContext.Response.Write(i.ToString());
Thread.Sleep(2000);
context.HttpContext.Response.Flush();
}
context.HttpContext.Response.End();
}
}
and this is an action that returns this result:
public ActionResult ProcessMessage()
{
return new ProgressiveResult();
}
You have to return false in click event handler to cancel submitting the form:
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus(); return false;"/>

Categories

Resources