private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
// string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
// imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
// return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
string cmd = "-y -ss 00:00:00 -to 00:00:10 -i " + inputPath + "\\" + fileName + " -vcodec copy -acodec copy " + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".mp4";
ConvertNow(cmd);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg\\ffmpeg.exe";
Process proc = new Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
//while (proc.HasExited == false)
//{
//}
}
Related
Good afternoon!
I have problems uploading images to a defined folder. As you can see, in my code I can upload to the cloudinary root, but not to a specific folder I created.
Cloudinary cloudinary = new Cloudinary(account);
string NomeImagem = "";
string TipoImagem = "";
string Versao = "";
byte[] binData = null;
string result = string.Empty;
if (Request.Files.Count > 0)
{
if (Request.Files["FotoURL"].ContentLength > 0)
{
using (BinaryReader b = new BinaryReader(Request.Files["FotoURL"].InputStream))
{
binData = b.ReadBytes(Request.Files["FotoURL"].ContentLength);
}
string teste = Convert.ToBase64String(binData);
byte[] imageBytes = Convert.FromBase64String(Convert.ToBase64String(binData));
using (MemoryStream ms = new MemoryStream(imageBytes))
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("."));
string diretorio = dir.FullName.ToString();
try
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(IdUsuario + "Perfiltemp.jpg", ms)
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = "v" + uploadResult.Version.ToString();
dados += "&FotoURL=http://res.cloudinary.com/diretor/aceleramei/image/upload/" + Versao + "/" + NomeImagem + "." + TipoImagem;
}
catch (Exception e)
{
string msg = e.ToString();
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(#"" + Server.MapPath("~") + "\\Content\\layout\\img\\300x200.gif")
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = "v" + uploadResult.Version.ToString();
// dados += "&FotoURL=http://res.cloudinary.com/diretor/image/upload/" + Versao + "/" + NomeImagem + "." + TipoImagem;
}
}
Solução
string NomeImagem = "";
string TipoImagem = "";
string Versao = "";
// string Pasta = "teste";
byte[] binData = null;
string result = string.Empty;
if (Request.Files.Count > 0)
{
if (Request.Files["FotoURL"].ContentLength > 0)
{
using (BinaryReader b = new BinaryReader(Request.Files["FotoURL"].InputStream))
{
binData = b.ReadBytes(Request.Files["FotoURL"].ContentLength);
}
string teste = Convert.ToBase64String(binData);
byte[] imageBytes = Convert.FromBase64String(Convert.ToBase64String(binData));
using (MemoryStream ms = new MemoryStream(imageBytes))
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("teste"));
string diretorio = dir.FullName.ToString();
try
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(IdUsuario + "Perfiltemp.jpg" , ms),
PublicId = $"aceleramei/{System.IO.Path.GetFileName(IdUsuario)}",
EagerAsync = true
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = "v" + uploadResult.Version.ToString();
dados += "&FotoURL=http://res.cloudinary.com/diretor/image/upload/" + Versao + "/" + NomeImagem + "." + TipoImagem;
}
catch (Exception e)
{
string msg = e.ToString();
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(#"" + Server.MapPath("~") + "\\Content\\layout\\img\\300x200.gif"),
PublicId = $"aceleramei/{System.IO.Path.GetFileName("")}",
EagerAsync = true
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = "v" + uploadResult.Version.ToString();
// dados += "&FotoURL=http://res.cloudinary.com/diretor/image/upload/" + Versao + "/" + NomeImagem + "." + TipoImagem;
}
}
}
else
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(#"" + Server.MapPath("~") + "\\Content\\layout\\img\\300x200.gif"),
PublicId = $"aceleramei/{System.IO.Path.GetFileName("")}",
EagerAsync = true
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = uploadResult.Version.ToString();
dados += "&FotoURL=";
}
}
else
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(#"" + Server.MapPath("~") + "\\Content\\layout\\img\\300x200.gif"),
PublicId = $"aceleramei/{System.IO.Path.GetFileName("")}",
EagerAsync = true
};
var uploadResult = cloudinary.Upload(uploadParams);
NomeImagem = uploadResult.JsonObj["public_id"].ToString();
TipoImagem = uploadResult.Format.ToString();
Versao = "v" + uploadResult.Version.ToString();
dados += "&FotoURL=";
i wrote two handlers but i need to write now only one handler using switch case how to write i tried but not working. please help me. this is my two handlers code i want that in switch case.please solve this problem
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Adds_uploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Adds_uploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
2nd Handler
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Fileuploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Fileuploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
I think the only difference if the upload path. I would suggest you to pass along another input form the view and then determine the upload path based on that.
i.e
you would have
//for case one
<input type='hidden' name='uploadType' value='files' />
//for case two
<input type='hidden' name='uploadType' value='adds' />
inside your individual file upload forms and then on your action method you can just use
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
and use this string in your fname construct. So your new method would be like
public void ProcessRequest(HttpContext context)
{
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = mappedDirectory + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath(mappedDirectory), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
I have my aspx pages , and some logic is written in code behind to bind the data of aspx pages.Now using wkhtmltopdf i am sending these files to convert into pdf files.Its work very well when the data is smaller in size however when the data comes in larger side for that page the wkhtmltopdf stops working and doesnt create any pdf file.
Can you suggest any way to overcome this problem. What i tried was limiting the data.. for example i have repeater control on my page if that controls binds 350 record i am only taking 20 records , but also if size of those 20 records are large it happens the same
the also next option i tried is my giving the parameter inside
Process myProcess = Process.Start(startInfo);
myProcess.WaitForExit(few seconds);
but it still doesnt work
Please suggest
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
This is the answer => what happen is when u start process , and wait for exit () both creates a deadlock somtimes which hammers the performance .. by adding readtoend() method before waitforexit() clears the deadlock and then continues further processing ...
this solves my problem.
The reason i am showing complete solution is that , wkhtmltopdf is very good for creating dynamic pdf files , but this is free tool as well and hence very limited documentation for this ..
private void ProcessHtmlToPdf(List<ExportToPdfCategories> lstExportToPdfCategories)
{
try
{
string pdfExportPath = string.Empty;
string PDFdeletePath = string.Empty;
string deletePath = string.Empty;
string PdfSavePath = string.Empty;
if (lstExportToPdfCategories != null)
{
foreach (var item in lstExportToPdfCategories)
{
path = "";
pdfExportPath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
PDFdeletePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString();
PdfSavePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
htmlpath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
deletePath = Server.MapPath(PDFdeletePath);
string ClearDirectory = Server.MapPath(PdfSavePath);
if (Directory.Exists(deletePath))
{
//Directory.Delete(ClearDirectory, true);
//Directory.Delete(deletePath, true);
}
if (!Directory.Exists(Server.MapPath(pdfExportPath)))
{
Directory.CreateDirectory(Server.MapPath(pdfExportPath));
}
string name =
pdfExportPath = pdfExportPath + "/" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-" + item.HeaderCategory + "_" + (drpYear.SelectedValue != "0" ? Convert.ToString(drpYear.SelectedValue) : System.DateTime.Now.Year.ToString()) + ".pdf";
objpath = Server.MapPath(pdfExportPath);
//this will create html mockup
//item.WebsiteUrl = CreateTemportHtmlFile(item.HeaderCategory, PdfSavePath, item.WebsiteUrl);
if (path == "")
{
path = CreateTemportHtmlFile(PdfSavePath, item.HeaderCategory);
}
HtmlToPdf(item.WebsiteUrl, objpath, path);
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-actusdocs.zip");
Response.ContentType = "application/zip";
objZip.Save(Response.OutputStream);
Response.End();
}
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("ProcessHtmlToPdf method : ", ex.Message + ex.StackTrace, objExpDetails);
}
}
//Method overloading
//this is for testing html pages(not in used during main running)
private string CreateTemportHtmlFile(string categoryName, string htmlMockupSavingPath, string websiteURL)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
htmlMockupSavingPath = Server.MapPath(htmlMockupSavingPath) + "\\" + categoryName + ".html";
StreamWriter sw;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(websiteURL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(htmlMockupSavingPath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(htmlMockupSavingPath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlMockupSavingPath;
}
private string CreateTemportHtmlFile(string PdfSavePath, string categoryName)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
PdfSavePath = Server.MapPath(PdfSavePath) + "\\BindHeader.html";
htmlpath = htmlpath.Substring(1);
htmlpath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + htmlpath + "/BindHeader.html";
string exportedYear = (drpYear.SelectedValue == "0" ? System.DateTime.Now.Year.ToString() : drpYear.SelectedValue);
StreamWriter sw;
if (categoryName == "MidYearAppraisal" || categoryName == "EndYearAppraisal")
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeaderforAppraisal.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
else
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeader.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(PdfSavePath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(PdfSavePath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlpath;
}
private void HtmlToPdf(string website, string destinationFile, string path)
{
try
{
string hrmlPath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + "/user/UserPdfReports/FooterPdfReports.html";
ProcessStartInfo startInfo = new ProcessStartInfo();
string switches = "";
switches += "--header-html " + path + " --footer-html " + hrmlPath;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
startInfo.Arguments = switches + " " + website + " " + destinationFile;
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("HtmlToPdf : ", ex.Message + ex.StackTrace, objExpDetails);
}
}
My multiple image upload code works fine. But while inserting the image path url in the database only one image path is saved. How can i save all the image path url's at once.
Here is my GetPictureData()
public string GetPictureData()
{
string retFileName = "";
try
{
if (((FileUpload1.PostedFile != null)))
{
if ((FileUpload1.PostedFile.ContentType.ToUpper().Contains("IMAGE")))
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//Stream inStream = hpf.InputStream;
//byte[] fileData = new byte[hpf.ContentLength];
//inStream.Read(fileData, 0, hpf.ContentLength);
String sTimeStamp = GetTimeStamp();
string iFileName = System.IO.Path.GetFileName(hpf.FileName);
string newFileName = iFileName.Replace(" ", "_");
string OutFile = Server.MapPath(ConfigurationManager.AppSettings["LocalImageDirectory"]) + "\\" + sTimeStamp + "_" + newFileName;
hpf.SaveAs(OutFile);
OutFile = ConfigurationManager.AppSettings["LocalImageDirectory"] + "\\" + sTimeStamp + "_" + newFileName;
retFileName = OutFile;
}
}
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
Response.Write(msg);
}
return retFileName;
}
and here is my UploadButton code
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
}
}
Thanks
You error lies in the fact that the GetPictureData loops over a collection of files, but only the last file is returned to the button event where you call the save to database code. Of course, only the last file will be saved in the database.
The workaround is to create a standalone method to save in the database where you pass the filename and the localAuctionID. You call this method inside the GetPictureData (renamed more correctly to SavePictureData) internal loop for each file to be saved
As a pseudocode (not tested)
private void SaveToDb(int localAutID, string filepath)
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) " +
"values(#auID, #file, 0); " +
" update auctionstep1 set ListingStatus = 'Photographed' " +
"where auctionid = #auID and (listingstatus <> 'Created' " +
"AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
DbParameter p1 = cmd.CreateParameter()
{ParameterName="#auID", DbType=DbType.Int32, Value=localAutID};
DbParameter p2 = cmd.CreateParameter()
{ParameterName="#file", DbType=DbType.AnsiString, Value=filepath};
db.ExecuteNonQuery(cmd);
}
And if SavePictureData call it inside the for loop
for (int i = 0; i < hfc.Count; i++)
{
.....
retFileName = OutFile;
SaveToDb(Convert.ToInt32(Session["localauctionid"]), retFileName);
}
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
The person only clicks the upload button once - hence only one image being saved.
Personally I would evaluate the way you have coded this. I would move the code you use to save the image to the db into a stand alone method and call it when the image upload is complete in GetPictureData()
The path of video(extension.wmv,.avi) is stored in SQL Server. And I have to create thumbnail and dispaly it on ASPX page.
Please share its code, if any body know this.
Thanks in Advance
For AVI you can use the below codeproject
http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library
For others try
http://sourceforge.net/projects/directshownet/
http://code.google.com/p/slimdx/
I have some bit of code for generating thumbnail video.
for that you need to have third party exe named "ffmpeg.exe" which is available for free. you can download from here
Now i have create function below which generate thumbnail video from original video.
you can change variable according to your requirement.
private bool SaveVideo(FileUpload fupload)
{
string VideoResolutionWidth = "400" ; //define video res. width
string VideoResolutionHeight = "280"; //define video res. height
string VideoThumbWidth = "100";//define jpg res. width
string VideoThumbHeight = "100"; //define jpg res. height
string VideoLocation = HttpContext.Current.Server.MapPath("~/ConverterFolder/Video/");
string ConverterPath = HttpContext.Current.Server.MapPath("~/ConverterFolder/");
String LargeFileName = "TestVideo.wmv"; // Thumb Video file name
string ThumbFileName= "Testvideo.jpg";
// Save Original video file first
if (fupload.PostedFile.FileName != "")
{
fupload.PostedFile.SaveAs(ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")));
}
if (System.IO.File.Exists(ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_"))))
{
string inipath = ConverterPath;
string flvCMD, flvArg;
string a_res_width, a_res_height, a_audioRate, a_frameRate, i_res_width, i_res_height;
a_res_width = VideoResolutionWidth;
a_res_height = VideoResolutionHeight;
i_res_width = VideoThumbWidth;
i_res_height = VideoThumbHeight;
a_audioRate = "22050";
a_frameRate = "15";
string VideoThumbResolution = i_res_width + "x" + i_res_height;
string VideoResolution = a_res_width + "x" + a_res_height;
String videoPATH = VideoLocation + "\\" + LargeFileName.Replace(" ", "_");
flvCMD = ConverterPath + "ffmpeg.exe";
flvArg = "-i " + ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")) + " -s " + VideoResolution + " -r " + a_frameRate + " -b 7500000 -ar " + a_audioRate + " -ab 48 " + videoPATH;
try
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = flvCMD;
process.StartInfo.Arguments = flvArg;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.Close();
process.Dispose();
if (System.IO.File.Exists(videoPATH))
{
Process process1 = new Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.RedirectStandardError = true;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.FileName = flvCMD;
process1.StartInfo.Arguments = "-i " + ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")) + " -an -ss 00:00:01 -r 1 -vframes 1 -s " + VideoThumbResolution + " -f mjpeg -y " + VideoLocation "\\" + ThumbFileName;
process1.Start();
string outputMeta1 = process1.StandardOutput.ReadToEnd();
process1.Close();
process1.Dispose();
}
else
{
return false;
}
}
catch (Exception)
{
}
}
return true;
}
Hope this will help you. happy coding....