I am using dropzone to upload the images. image will be uploaded to server folder while image name will be saved in database table.
here is my code :
public class FormUploader_dz : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("/images/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
Service.SaveImage(strFileName, context.Session["Id"].ToString());
}
}
context.Response.Write(str_image);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Service file code : which will insert image name into table.
public static void SaveImage(string strImage, string Id)
{
string strSql = #"update tablename set image=#image where id=#Id
";
SqlParameter[] objSqlParameter ={
new SqlParameter("#image",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}
Now here problem is i have 4 columns in table to save 4 different image name. what i am actually doing is allowing user to upload max 4 images. i have 4 columns as img1, img2, img3, img4.
here how to insert/update image name into table, as their are 4 diffrent columns for images!
here if user wants he can upload 4 images. so how to decide that in which column the image name will go?????
any suggestions??????
I am not sure about the exact syntax but something like this could work.
// **********************************
int counter = 0; // set up the counter
// **********************************
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
// **********************************
counter++; // increment the counter
// **********************************
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
// **********************************
Service.SaveImage(strFileName, context.Session["Id"].ToString(), counter); // add counter variable to the path.
// **********************************
}
}
// **********************************
// add a column variable and then add it to your column name. like string columnName = "img+columnCount"
// **********************************
public static void SaveImage(string strImage, string Id, int columnCount)
{
// **********************************
string strSql = #"update tablename set img#columnName=#image where id=#Id";
// **********************************
SqlParameter[] objSqlParameter ={
new SqlParameter("#strImage",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}
Related
I have filename like this: 一個例子.pdf
I want to save the filename in a SQL Server table and read it from the SQL Server table. How do you do that?
This is the code:
class Bestand
{
public void Add(string filePath, DateTime fileDate, string fileName = "")
{
Bestand bestand = this.CurrentBestand;
if (filePath.Length > 0 && CanReadFile(filePath))
{
Binary bin = new Binary();
bin.Data = new System.Data.Linq.Binary(File.ReadAllBytes(filePath));
bestand.BestandsDatum = fileDate;
bestand.BestandsNaam = String.IsNullOrEmpty(fileName) ? Path.GetFileName(filePath) : Encoding.UTF8.GetBytes(fileName)[0].ToString();
bestand.Binary = bin;
}
}
public void Save(string filePath)
{
byte[] buffer = Data.ToArray();
System.IO.File.WriteAllBytes(filePath, buffer);
}
…
}
and call this to save the file:
documents[0].Add(beFile.Value, dtpDate.Value);
and call this to open the file:
public static void ViewBestand(IBestand bestand)
{
string orgFilepath = Path.Combine(TempDocumentFolder, bestand.FileName);
string filepath = orgFilepath;
int tmpCounter = 0;
while (File.Exists(filepath) && tmpCounter < 100)
{
tmpCounter++;
filepath = Path.Combine(TempDocumentFolder, Path.GetFileNameWithoutExtension(orgFilepath) + "_" + tmpCounter.ToString() + Path.GetExtension(orgFilepath));
}
bestand.Save(filepath);
ViewFile(filepath);
}
Change the type of your column to nvarchar(100). varchar cannot store Unicode characters, cause it's single byte, Unicodeis double byte.
More you can read here.
I am uploading multiple images to my folder asynchronously using XMLHttpRequest. After the all images are completely loaded to folder I need to send an email which contains these images in the email body part as well as attachment. My question is how do I check if all the images are completely uploaded to my folder. I have tried the following:
$scope.UploadFile = function (inputFile) {
var j = inputFile.length;
var filenames = [];
for (var i = 0; i < inputFile.length; i++) {
$scope.UploadFileIndividual(inputFile[i].file,
inputFile[i].file.name,
inputFile[i].file.type,
inputFile[i].file.size,
i, inputFile.length);
filenames[i] = inputFile[i].file.name;
j--;
}
if (j == 0)
{
$http({
method: 'POST',
url: '/RFQ/SendEmail/',
data: { RFQValues: $scope.RFQData, fileNames: filenames}
}).success(function (response, status, headers, config) {
if (response == true) {
window.location.href = '/CheckOut/ThankYou';
}
}).error(function (response, status, headers, config) {
// alert('Your Selection Not Added to Cart');
});
}
} ;
$scope.UploadFileIndividual = function (fileToUpload, name, type, size, index, fileArrayLength) {
var reqObj = new XMLHttpRequest();
//open the object and set method of call(get/post), url to call, isasynchronous(true/False)
reqObj.open("POST", "/RFQ/UploadFiles", true);
//set Content-Type at request header.For file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");
//Set Other header like file name,size and type
reqObj.setRequestHeader('X-File-Name', name);
reqObj.setRequestHeader('X-File-Type', type);
reqObj.setRequestHeader('X-File-Size', size);
// send the file
reqObj.send(fileToUpload);
};
This is my controller method to upload images:
public virtual string UploadFiles(object obj)
{
try
{
var length = Request.ContentLength;
var bytes = new byte[length];
Request.InputStream.Read(bytes, 0, length);
var fileName = Request.Headers["X-File-Name"];
var fileSize = Request.Headers["X-File-Size"];
var fileType = Request.Headers["X-File-Type"];
string path = #"~\images\Client Images";
string subPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString();
string finalPath = Server.MapPath(path + #"\" + subPath);
if (!Directory.Exists(finalPath))
Directory.CreateDirectory(finalPath);
var saveToFileLoc = finalPath + #"\" + fileName;
// save the file.
var fileStream = new FileStream(saveToFileLoc, FileMode.Create, FileAccess.ReadWrite);
fileStream.Write(bytes, 0, length);
fileStream.Close();
var usrid = Convert.ToInt32(System.Web.HttpContext.Current.Session["UserId"].ToString());
using (DataContext _db = new DataContext())
{
int RFQId = _db.RFQDetailss.OrderByDescending(x => x.RFQId).Where(x => x.UserId == usrid && EntityFunctions.TruncateTime(x.RFQ_CreatedDate) == EntityFunctions.TruncateTime(DateTime.Now)).Select(y => y.RFQId).FirstOrDefault();
RFQClientImage objClientImage = new RFQClientImage();
objClientImage.RFQId = RFQId;
objClientImage.ImagePath = #"images\Client Images\" + subPath + #"\" + fileName;
_db.RFQClientImages.Add(objClientImage);
_db.SaveChanges();
}
return string.Format("{0} bytes uploaded", bytes.Length);
}
catch
{
return "";
}
}
I have then checked on js side if all files are sent for uploading and then in controller also I am checking if currently uploaded files exists in the folder by following code:
public JsonResult SendEmail(RFQFormInfo RFQValues, string[] fileNames)
{
bool IsMailSent = false;
try
{
string directoryPath = #"~\images\Client Images\";
string subDirectoryPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString() + #"\";
//string[] fileEntries = Directory.GetFiles(Server.MapPath(directoryPath + subDirectoryPath));
string targetPath = Server.MapPath(directoryPath + subDirectoryPath);
IsMailSent = checkifImageUploaded(RFQValues, getFilesList(targetPath), fileNames);
return Json(IsMailSent, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(IsMailSent, JsonRequestBehavior.AllowGet);
}
}
public bool checkifImageUploaded(RFQFormInfo RFQValues, IEnumerable<string> fileEntries, string[] fileNames)
{
bool IsMailSent = false;
try
{
int counter = 0;
string directoryPath = #"~\images\Client Images\";
string subDirectoryPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString() + #"\";
string targetPath = Server.MapPath(directoryPath + subDirectoryPath);
foreach (string filename in fileNames)
{
var currentFile = Server.MapPath(directoryPath + subDirectoryPath + filename);
foreach(var file in fileEntries)
{
if (file.Equals(currentFile))
{
counter++;
break;
}
}
if (counter == fileNames.Length)
break;
}
if (counter == fileNames.Length)
{
IsMailSent = SendRFQMail(RFQValues, fileNames);
return IsMailSent;
}
else
checkifImageUploaded(RFQValues, getFilesList(targetPath), fileNames);
return IsMailSent;
}
catch
{
return IsMailSent;
}
}
public IEnumerable<string> getFilesList(string targetDirectory)
{
var fileEntries = Directory.EnumerateFiles(targetDirectory);
return fileEntries;
}
but my checkIfImageUploaded() function throws stack overflow exception. I understand it is because my code is ending up into infinite loop or recursion but what I don't understand is at what point is my code ending into infinite recursion and how to solve it.
Please help me out. Thanks in advance.
Is there a simple or a more compact way to do this with a large number of files with one check-box (checked/unchecked), i have i think few thousand lines to put inside the code and i can sort them by year, or by type:
private void CheckBox()
{
try
{
switch (checkBox.IsChecked)
{
case true:
{
const string disable_picture100 = "images/disabled/picture100.png";
const string picture100 = "images\\disabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, disable_picture100, content.FileRoot);
const string disable_picture101 = "images/disabled/picture101.png";
const string picture101 = "images\\disabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, disable_picture101, content.FileRoot);
const string disable_picture102 = "images/disabled/picture102.png";
const string picture102 = "images\\disabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, disable_picture102, content.FileRoot);
UpdateImage();
}
break;
case false:
{
const string enable_picture100 = "images/enabled/picture100.png";
const string picture100 = "images\\enabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, enable_picture100, content.FileRoot);
const string enable_picture101 = "images/enabled/picture101.png";
const string picture101 = "images\\enabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, enable_picture101, content.FileRoot);
const string enable_picture102 = "images/enabled/picture102.png";
const string picture102 = "images\\enabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, enable_picture102, content.FileRoot);
UpdateImage();
}
break;
}
}
catch (Exception ex)
{
//ignored
}
}
Thank you!
List<string> fileNames = new List<string>(); //suppose you have names of files in a list
foreach(var name in fileNames)
{
if(checkBox.IsChecked)
{
Records[name].ReplaceContents
("images/disabled/" + name, "images\\disabled\\" + name, content.FileRoot);
}
else
{
Records[name].ReplaceContents
("images/enabled/" + name, "images\\enabled\\" + name, content.FileRoot);
}
}
Using the code below you can specify a directory (where the string says "FilePath". It gets all files with the extension .png
Then it checks once if the checkbox is checked or not.
And then loops over all the files in the enumerator
var allPngFilesInGivenDirectory = Directory.EnumerateFiles("FilePath").Where(x => x.ToLower().EndsWith(".png"));
var fileEnumerable = allPngFilesInGivenDirectory.GetEnumerator();
string partialPath = checkBox.IsChecked ? "enabled" : "disabled";
while (fileEnumerable.MoveNext())
{
string file = Path.GetFileName(fileEnumerable.Current);
string disable_picture = "images/" + partialPath + "/" + file;
string picture = "images\\" + partialPath + "\\" + file;
Records[picture].ReplaceContents(imagesPath, disable_picture, content.FileRoot);
UpdateImage();
}
Is this roughly what you are looking for?
string pictureName;
string newPictureName;
List<string> fileNames = new List<string>();
foreach(var name in fileNames)
{
if (checkBox.IsChecked)
{
pictureName = "images\\disabled\\" + name + ".png";
newPictureName = "images/disabled/" + name + ".png";
}
else
{
pictureName = "images\\enabled\\" + name + ".png";
newPictureName = "images/enabled/" + name + ".png";
}
}
Records[pictureName].ReplaceContents(imagesPath, newPictureName, content.FileRoot);
Let me know if not.
With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}
I have get my website path using HttpRuntime.AppDomainAppPath (like this C:/personal/Website/page.aspx)
Web service is always located on page.aspx parent of parent folder (like this C:/personal/Service/service.asmx ). I get the webservice-path using a ABC.dll in servicePath variable like this string servicePath="C:/personal/Service/service.asmx".
How to check service path against website path?
If (GetWebPath()== GetServicePath())
{
// ... do something
}
private string GetWebPath()
{
string path = HttpRuntime.AppDomainAppPath;
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = array[array.Length - 2];
break;
}
path = path.Replace(#"\" + removeString + #"\", "");
return path;
}
private string GetServicePath()
{
string path = #"C:\MNJ\OLK\ABC.asmx"
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = #"\" + array[array.Length - 2] + #"\" + array[array.Length - 1];
path = path.Replace(removeString, "");
break;
}
return path;
}
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
if(Path.GetDirectory(Path.GetDirectoryName(servicePath))==Path.GetDirectoryName(webPath)
{
//You do something here
}
You have to up page to parent folder using Path.GetDirectoryName()
Try this:
System.Web.Server.MapPath(webPath);
This will return the physical file path of the currently executing web file.
More information can be found here: System.Web.Server
Providing you want to check the following pathes:
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
you should call
string webPathParentDir = GetParentDirectoryName(webPath);
string servicePathParentDir = GetParentDirectoryName(servicePath);
if (servicePathParentDir.Equals(webPathParentDir, StringComparison.OrdinalIgnoreCase))
{
// ... do something
}
with method:
private string GetParentDirectoryName(string path)
{
string pathDirectory = Path.GetDirectoryName(servicePath);
return new DirectoryInfo(pathDirectory).Parent.FullName;
}