I'm adding a row to Videos and then I want to use that same ID as the video's physical filename. so I need to add the row without the filename, and then use the ID I get, then update that row with the filename. I'm just now sure how to do that.
public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
{
Video v = new Video();
v.Name = VideoName;
v.Report = Report;
db.Videos.Add(v);
var filename = v.ID + "." + Path.GetExtension(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
file.SaveAs(path);
v.FileName = filename;
//** update Row here with filename
db.SaveChanges();
//** redirect back to Report Details (need to figure out how do do this too)
return RedirectToAction(Report);
}
Assuming that you have an auto incrementing primary key for ID in your database, you need to call save changes before referencing the ID property. You have to save the entity to the database so that the ID can be assigned.
public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
{
Video v = new Video();
v.Name = VideoName;
v.Report = Report;
db.Videos.Add(v);
db.SaveChanges();
var filename = v.ID + "." + Path.GetExtension(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
file.SaveAs(path);
v.FileName = filename;
db.SaveChanges();
//** redirect back to Report Details (need to figure out how do do this too)
return RedirectToAction(Report);
}
Since 'filename' is only a combination of the Id and the file extension, why not just save the file extension and do the concatenation when you need to reference the video. This would reduce your calls to the database back down to one and save a little on DB storage
public ActionResult UpVideo(Report Report, string VideoName, HttpPostedFileBase file)
{
Video v = new Video();
v.Name = VideoName;
v.FileName = Path.GetExtension(file.FileName);
v.Report = Report;
db.Videos.Add(v);
db.SaveChanges();
var filename = v.ID + "." + v.FileName;
var path = Path.Combine(Server.MapPath("~/App_Data/video_uploads"), filename);
file.SaveAs(path);
//** redirect back to Report Details (need to figure out how do do this too)
return RedirectToAction(Report);
}
Related
public ActionResult Import(HttpPostedFileBase currencyConversionsFile)
{
string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv";
string folderPath = Server.MapPath("~/Files/");
string filePath = Server.MapPath("~/Files/" + filename);
currencyConversionsFile.SaveAs(filePath);
string[] csvData = System.IO.File.ReadAllLines(filePath);
//the later code isn't show here
}
I know the usual way to convert httppostedfilebase to String array, which will store the file in the server first, then read the data from the server. Is there anyway to get the string array directly from the httppostedfilebase with out store the file into the server?
Well you can read your file line by line from Stream like this:
List<string> csvData = new List<string>();
using (System.IO.StreamReader reader = new System.IO.StreamReader(currencyConversionsFile.InputStream))
{
while (!reader.EndOfStream)
{
csvData.Add(reader.ReadLine());
}
}
From another thread addressing the same issue, this answer helped me get the posted file to a string -
https://stackoverflow.com/a/40304761/5333178
To quote,
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
Splitting the string into an array -
string[] csvData = new string[] { };
csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
I'm uploading an image to my site using the following code,
The Image uploading just fine but, how ever
I need to fix the following things :
-I'm getting this kind of Url
C:\Users\Me\Documents\Visual Studio 2013\Projects\Wow\WowMvc5\WowMvc5\images\gallery\Picture 022.jpg,
Instead of relevant folder Url
-I thing in order to avoid an error of 2 images this the same name it would be better to create a folder under images for each image (or any better idea )
Thank you for your time
public async Task<ActionResult> Create([Bind(Include = "TakeAwayId,TakeAwayName,description,Price,DishUrl,quantity,DishesAmount,GenreId")] TakeAway takeaway)
{
var path = Server.MapPath("~/Images/gallery/");
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
string SavedFileName = System.IO.Path.GetFileName(file.FileName);
SavedFileName = Server.MapPath
("~" + "/images/gallery/" + SavedFileName);
file.SaveAs(SavedFileName);
takeaway.DishUrl = SavedFileName;
}
if (ModelState.IsValid)
{
db.takeaway.Add(takeaway);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.genre, "GenreId", "GenreName", takeaway.GenreId);
return View(takeaway);
}
What I would do is name and save each picture using a HashCode.
By definition, It's very improbable that 2 different strings, when transformed using a hash algorithm, will have the same output. Just to be sure, add a random string to the original name of the image.
string newName = (oldName + random).GetHashCode().ToString()
filename_1.jpg
where cnt is incremental count
if(file.exists()
{
string cnt = file.split("");
String newFileName = filename+""+(cnt+1)+".jpg";
}
I want to create and return a CSV file from a controller but I have several errors in IE8 with Chrome frame, because the controller returns a file and again calls post two times.
In my view I have a simple submit button:
Controller:
public ActionResult File()
{
string billcsv = "account_ref,line1,line2,line3";
var data = Encoding.UTF8.GetBytes(billcsv);
string filename = "billfor.csv";
var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "filename.csv";
//Response.AddHeader("Content-Disposition", cd.ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=filename.csv");
return File(data, "text/csv", filename);
}
Thanks.
Try this:
public FileResult File()
{
string billcsv = "account_ref,line1,line2,line3";
var data = Encoding.UTF8.GetBytes(billcsv);
string filename = "billfor.csv";
File(data, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}
this is my controller class:-
public class PlantHeadController : Controller
{
private WOMSEntities2 db = new WOMSEntities2();
//
// GET: /PlantHead/
Document doc = new Document();
static String[] tt=new String[20];
public ActionResult Index()
{
ViewBag.productCode = new SelectList(db.Product, "ID","code");
return View();
}
public void Convert()
{
PdfWriter.GetInstance(doc, new
FileStream((Request.PhysicalApplicationPath + "\\Receipt3.pdf"),
FileMode.Create));
doc.Open();
PdfPTable table = new PdfPTable(2);
doc.AddCreationDate();
PdfPCell cell = new PdfPCell(new Phrase("Receipt"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("ahym");
table.AddCell("ram";
table.AddCell("good");
table.AddCell("morning");
String rawGroup = "";
foreach (String lll in raw)
rawGroup = rawGroup + lll+" ";
table.AddCell("" + rawGroup);
doc.Add(table);
doc.Close();
Response.Redirect("~/Receipt3.pdf");
}
}
whenever i press submit button to make pdf file then this error window is opened:-
means pdf is not generated successfully. in some cases old pdf is shown. please suggest me what should i do?
Everything looks good for the most part above (except a missing parenthesis on table.AddCell("ram"; which I assume is just a typo and you could also do with some using statements). I don't know why you would get an error but the reason that you're getting the same PDF is almost definitely because of browser caching. You could append a random querystring to the file but I'd recommend instead skipping the file completely and writing the binary stream directly. This way you can control the caching and you don't have to work about browser redirection. The below code should work for you (its targeting 5.1.1.0 depending on your version you may or may not be able to use some of the using statements).
EDIT
I donwgraded my code to not use the IDisposable interfaces found in newer versions, this should work for you now. (I don't have access to a C# compiler so I didn't test it so hopefully this works.)
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document());
PdfWriter writer = PdfWriter.GetInstance(doc, ms));
doc.Open();
doc.AddCreationDate();
PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Phrase("Receipt"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("ahym");
table.AddCell("ram");
table.AddCell("good");
table.AddCell("morning");
String rawGroup = "";
foreach (String lll in raw)
{
rawGroup = rawGroup + lll + " ";
}
table.AddCell("" + rawGroup);
doc.Add(table);
doc.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Receipt3.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(ms.ToArray());
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I have an asp.net mvc action that returns a file result. Behind the scenes, it's just returning a file from a directory. FilePathResult requires a content type, but I don't know that.
What is the proper way to return a file result if I only have the path to the file available?
Take the file extension, and look it up in the registry. The entry for it will have a "Content type" property.
Here's a complete example of returning a FilePathResult from a controller action:
string filePysicalPath, fileName; //these need to be set to your values.
var reg = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey( Path.GetExtension( filename ).ToLower() );
string contentType = "application/unknown";
if ( reg != null )
{
string registryContentType = reg.GetValue( "Content Type" ) as string;
if ( !String.IsNullOrWhiteSpace( registryContentType ) )
{
contentType = registryContentType;
}
}
return File( filePysicalPath, contentType, filename );
This approach won't hit the registry
private FileResult CreateFileResult(byte[] file, string fileName)
{
var cd = new ContentDisposition
{
FileName = fileName,
Inline = false
};
this.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return this.File(file, MediaTypeNames.Application.Octet);
}