"ilan" is a table in my database, ilan has a column named "kapak_foto".
Here is my code:
[HttpPost]
[ValidateInput(false)]
public ActionResult ilanver(ilan ilan,HttpPostedFileBase kapak_foto)
{
if (kapak_foto != null)
{
string kapakname = Path.GetFileNameWithoutExtension(kapak_foto.FileName)
+ "-" + Guid.NewGuid() + Path.GetExtension(kapak_foto.FileName);
Image orjres = Image.FromStream(kapak_foto.InputStream);
orjres.Save(Server.MapPath("~/Content/images/pics" + kapakname));
ilan dbres = new ilan();
dbres.kapak_foto = "/Content/images/pics" + kapakname;
}
The html part:
#using (Html.BeginForm("ilanver", "ilanver", FormMethod.Post, new { enctype="multipart/form-data" }))
{ <input type="file" name="kapak_foto"/>}
Firstly; the code is
orjres.Save(Server.MapPath("~/Content/images/pics/" + kapakname));
Second; if you will use the path of saved file, you must take the file location into antoher variable before to save;
var filePath = "/Content/images/pics/" + kapakname;
orjres.Save(Server.MapPath(filePath));
ilan dbres = new ilan();
dbres.kapak_foto = filePath;
// ... the other codes...
db.ilan.add(dbres); // if your databse name defined before as db!
db.SaveChanges();
If the filePath is correct for to save file, it can be usable for url.
Related
I'm creating a page with multiple file uploader in MVC.
What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.
My controller looks like this:
public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
{
var guid = Guid.NewGuid().ToString();
someclass.filename = guid;
int i = 0;
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = guid + "" + i + ".jpg";
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}
db.someclasses.Add(someclass);
db.SaveChanges();
return RedirectToAction("Preview");
}
And my view looks like this
<input type="file" name="files" id=1>
<input type="file" name="files" id=2>
Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .
Well, I am not very familiar with HTML inputs, but I think you should use "multiple" attribute in you SINGLE file input tag.
Or rename "files" to "files[]".
Look at this
try this way if you have multiple file controls on view.
you can even have Guid initialized for each file and can ignore appending i to the name.
public class MultipleFilesForm
{
public HttpPostedFileBase file1 {get;set;}
public HttpPostedFileBase file2 {get;set;}
}
action method as
public ActionResult Home(MultipleFilesForm form)
{
var guid = Guid.NewGuid().ToString();
someclass.filename = guid;
int i = 0;
if(form.file1 != null)
{
var file = form.file1;
if (file.ContentLength > 0)
{
var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}
if(form.file2 != null)
{
//handle file
}
...
}
[UPDATE]
try this way
try this as well.
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = guid + i.ToString() + Path.GetExtension(file.FileName));
var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
file.SaveAs(path);
i++;
}
}
my code is like this, how can i add the prefix like "123_" to the front of the filename when the user uploads like 1.jpg, and then change it to 123_1.jpg to the server?
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
allowedExtensions: ["jpg", "pdf"],
template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>drag the files to here to upload</span></div>' +
'<div class="qq-upload-button">upload files</div>' +
'<ul class="qq-upload-list"></ul>' +
'</div>',
action: '#Url.Action("upload", new { staffId = Model.StaffId })'
});
</script>
Pretty simple,
public ActionResult SaveFile(HttpPostedFileBase FileUpload)
{
string fileName = "";
if (FileUpload != null && FileUpload.ContentLength > 0)
{
fileName = "123_"+ Path.GetFileName(FileUpload.FileName);
//rest code
Here I add product and save path of image, everything works fine and image path is saved
public ActionResult AddProduct(Product p, HttpPostedFileBase prodImg, decimal[] price)
{
try
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(prodImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
prodImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
p.ImagePath = relitivePath;
p.Blocked = false;
new ProductsBL().AddProduct(p);
ViewData\["msg"\] = "Successfuly";
}
catch(Exception ex)
{
}
ModelState.Clear();
return View();
}
When trying to update image path it gives me error shown on screenshot
public ActionResult Update(Product modifieDetails, HttpPostedFileBase updImg)
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(updImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
updImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
modifieDetails.ImagePath = relitivePath;
modifieDetails.Blocked = false;
new ProductsBL().UpdateProduct(modifieDetails);
return RedirectToAction("ListProduct");
}
[1]: http://i.stack.imgur.com/wgE88.png
You need to split this up:
new ProductsBL().AddProduct(p);
In order to save updates to an entity back to the store, you have to set "IsModified" on the entity, and then save the context. Like so...
using (ProductsBL context = new ProductsBL()) {
var p = (some query to get it from the store);
p.ImagePath = relitivePath;
p.Blocked = false;
p.IsModified = true;
context.SaveChanges();
}
As it is, you're creating a new entity and adding that to the store, not updating the existing one.
And, if you're coding in English, please fix the spellings: Modify, Relative, absolute.
I am trying to save a list of files to the file system and the path to EF. I haven't found a complete tutorial online so I've mashed up a couple of blog posts to scope out what I need. I can save 1 file but I can't save multiple files. I know why though. It is because the list gets reinitialized after every file. I've tried to move things in and out of scope and tried initializing variables in other ways. Can someone take a look at my controller and see what I can do to fix?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "Id")] Incident incident, IEnumerable<HttpPostedFileBase> upload)
{
if (ModelState.IsValid)
{
if (upload != null)
{
int MaxContentLength = 1024 * 1024 * 10; //10 MB
string[] AllowedFileExtensions = new string[] { ".jpg, ", ".gif", ".png", ".pdf", ".doc", "docx", "xls", "xls" };
foreach (var file in upload)
{
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower()))
{
ModelState.AddModelError("Upload", "Document Type not allowed. Please add files of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("Upload", "Your file is too large. Maximum size allowed is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
var photo = new FilePath
{
FileName = Path.GetFileName(file.FileName),
FileType = FileType.Document
};
incident.FilePaths = new List<FilePath> { photo };
}
}
ModelState.Clear();
}
db.Incidents.Add(incident);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize the list before loop:
incident.FilePaths = new List<FilePath>();
foreach(var file in upload)
{
// your code except last line
incident.FilePaths.Add(photo);
}
// rest of your code
I Make Upload Image In Asp.Net And I Really Save The Image In The Data Base But When i Want To Make A Query To Select The Image It Return The Source Of The Image With No Image Please I Want Any One Know The Solution Please Help Me.`enter code here This Is The Controller Code:
public ActionResult UpLoadImage(HttpPostedFileBase file)
{
if (file != null)
{
UpLoadDBEntities context = new UpLoadDBEntities();
file = Request.Files[0];
string filename = file.FileName;
string contenttype = file.ContentType;
string full = filename + " " + contenttype;
//string path = System.IO.Path.Combine(
// Server.MapPath("~/images/") + file.FileName);
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
Image_table it = new Image_table();
it.Image_Path = filename;
context.Image_table.Add(it);
context.SaveChanges();
}
return View();
}
public JsonResult ShowImage()
{
UpLoadDBEntities context = new UpLoadDBEntities();
Image_table it = new Image_table();
var showimage = (from itbl in context.Image_table
where itbl.ID == 8
select new { itbl.Image_Path });
return Json(showimage , JsonRequestBehavior.AllowGet);
}
You are setting the path as
it.Image_Path = filename;
Yet it gets store on the server as
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
I hope you can see it needs to be it.Image_Path = "~/Images/" + filename;. Also, make sure folks can actually access the path through IIS.