File upload after dropdown selected - c#

I have a Dropdown list & file uploader.Here i need, when dropdown list selected & after that need to load the file uploader.In my coding always it shows there's no File.
Here i need SelectedValue passes to the database with file uploader.
My Code
protected void drpuser_SelectedIndexChanged(object sender, EventArgs e)
{
Guid SelectedUserId =Guid.Parse(drpuser.SelectedValue);
FileUploader();
}
FileUploader
public void FileUploader()
{
// var user = Membership.GetUser();
if (Roles.IsUserInRole("Administrator"))
{
Guid SelectedUserId = Guid.Parse(drpuser.SelectedValue); //<-- value correct
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
Guid UserGUID = (Guid)Membership.GetUser().ProviderUserKey;
string UserFolderPath = "~/UploadedFiles/" + UserGUID;
System.IO.Directory.CreateDirectory(Server.MapPath(UserFolderPath));
string savedFileName = Path.Combine(Server.MapPath(UserFolderPath), fileName);
string FullPath = UserFolderPath + "/" + fileName;
file.SaveAs(savedFileName);
DataAccess da = new DataAccess();
da.AddAdminFiles(UserGUID, FullPath, DateTime.Now, true, SelectedUserId);
}
}
else
{
}

I'm thinking that the file will only be posted on actual submit.. Im not sure if an AutoPostBack will automatically submit file over and over.. probably too much HTTP Overhead.
If you can, add a "submit" button instead, and have the user choose an item from the drop down list and supply a file. Then when user submits, look for the HTTP file, and it should be in the Request Object.

Related

Adding a text file to an application

I have been learning c# for a short time and am creating some desktop project. I would like to add an empty text file using RadWindow.Prompt its name and then add the text file for editing. Currently this is handled using openFileDialog.
The principle of operation should resemble adding a file in OneNote, if anyone has used it. RadWindow.Prompt will display a window in which the user will type the name of the file he wants to create and then the file will be added, but it will be an empty file for editing (text document).
I would ask for a hint.
private async void AddFile(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openFileDialog = new OpenFileDialog();
bool response = openFileDialog.ShowDialog();
if (response == true)
{
string filepath = openFileDialog.FileName;
string fileName = Path.GetFileName(filepath);
try
{
File.Copy(filepath, Settings[0].SettingValue + "\\" + fileName, true);
long size = 1024;
await _db.FileInsert(1, fileName, size, Settings[0].SettingValue + "\\" + fileName, "a", "FileAddTest", "FileAddTest");
MessageBus.Default.Publish(new RefreshMessage(this, "Refresh"));
}
catch
{
RadWindow.Alert("File not add");
}
}
}
Maybe instead of that, create model with for example two properties and add to DB context.
code concept:
class File
{
public string FileName {get;set;}
[Column(TypeName="text")]
public string FileContent {get;set;}
}
void SomeAddFileButton()
{
var file = new File()
{
FileName = someInputField.Text;
};
dbContext.Files.Add(file);
}
EF Core: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app
'text' type: https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql

how to store and retrieve multiple values inside single session variable

i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.
i am trying to add file names in session.
the problem here is that it doesn't add multiple file names inside single session
here is my code :
string imageSessList = context.Session["imageNames"].ToString(); //if i put this line at the begining, then the debugger doesn't even moves to foreach block
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
string destFileName = "";
List<string> lstImageNames = new List<string>();
// else upload file
if (!string.IsNullOrEmpty(fileName))
{
if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
{
if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
{
// generate file name
destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
//Save image names to session
lstImageNames.Add(destFileName);
context.Session["imageNames"] = lstImageNames;
file.SaveAs(destFilePath);
strMessage = "Success " + destFileName;
}
else
{
strMessage = "File Size can't be more than 5 MB.";
}
}
else
{
strMessage = "File type not supported!";
}
}
} // foreach
context.Response.Write(strMessage);
}
here i am able to add only single filename to session, not multiple.
how to store and maintain multiple file names in single session :
context.Session["imageNames"]
you need to get current list from session
List<string> lstImageNames= (List<string>)Session["imageNames"];
if(lstImageNames==null)
lstImageNames = new List<string>(); // create new list in the first time
now add new item to it.
lstImageNames.Add(destFileName);
set back to session
context.Session["imageNames"] = lstImageNames;

Sharepoint uploaded file name was changed by server event. How to retrieve it?

I'm uploading file to Sharepoint server using this code:
ClientOM.File uploadFile = null;
try {
string fileRef = serverRelativeURL + msg.Message.FileName;
FileCreationInformation fileCreationInformation = new FileCreationInformation() {
Content = msg.Content,
Url = fileRef,
Overwrite = true
};
uploadFile = _currentList.RootFolder.Files.Add(fileCreationInformation);
_currentContext.ExecuteQuery();
And file uploaded. But on server we have event that adds some random string to the file title. So fileRef is not relevant after upload.
And we need to set the Author of the file. For this we have to retrieve file and update this propery. I do it with this sample:
string fileName = serverRelativeURL + msg.Message.FileName;
uploadFile = _currentContext.Web.GetFileByServerRelativeUrl(fileName);
_currentContext.Load(uploadFile);
uploadFile.ListItemAllFields["Author"] = _currentUser;
uploadFile.ListItemAllFields["Editor"] = _currentUser;
uploadFile.ListItemAllFields.Update();
_currentContext.ExecuteQuery();
And on ExecuteQuery() I get an Exception "File not found". But if I copy path from Sharepoint (with that random string) everything works Ok.
So the question is: Is there other way to retrieve file? By id for example? because when we uploading file, instance "uploadFile" does not have much of useful information.
Method 1:
Keep track of the filename, and then use this code to retrieve it directly.
public FileInformation GetFileFromAttachment(int itemId, string filename)
{
FileInformation file = null;
//continue here
if (new FileInfo(filename).Name != null)
{
CSOMUtils.ExecuteInNewContext(QueryConfig.siteUrl, delegate(ClientContext clientContext)
{
clientContext.Credentials = QueryConfig.credentials;
clientContext.Load(clientContext.Web, l => l.ServerRelativeUrl);
clientContext.ExecuteQuery();
List oList = clientContext.Web.Lists.GetByTitle(ListName);
clientContext.ExecuteQuery();
string url = string.Format("{0}/Lists/{1}/Attachments/{2}/{3}",
clientContext.Web.ServerRelativeUrl,
ListName,
itemId,
filename);
var f = clientContext.Web.GetFileByServerRelativeUrl(url);
clientContext.Load(f);
clientContext.ExecuteQuery();
file = File.OpenBinaryDirect(clientContext, f.ServerRelativeUrl);
});
}
return file;
}
Method 2:
You can use ServerRelativeUrl to get the folder containing all the attachments.
https://msdn.microsoft.com/library/office/microsoft.sharepoint.client.folder.serverrelativeurl.aspx
https://sharepoint.stackexchange.com/questions/132008/reliably-get-attachments-for-list-item

Files on the server are overwritten with files of the same name

I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();

Load picture from SQL database asp.net C#

I have avatars stored in a database. I have used the the data type image for the avatars. I want to load the avatar of a user into an image control, but i cant get it to work. I have tried this code without any luck:
public void GetUserAvatar()
{
string username = Convert.ToString(Session["username"]);
var image = from u in dc.Users
where u.username == username
select u.image;
imgAvatar.Controls.Add(image);
}
I think i might have to save the images to a folder and then save the file path in the database instead. This seems to be easier and smoother. Any ideas?
I ended up saving the image to a folder and then saving the path to the database. My code for image uploading now looks like this:
public void addImage()
{
if (fuAvatar.PostedFile.ContentType.ToLower().StartsWith
("image") && fuAvatar.HasFile)
{
string saveLocation = Server.MapPath("savedAvatars/");
string fileExtension = System.IO.Path.GetExtension(fuAvatar.FileName);
string fileName = Convert.ToString(Session["userid"]);
string savePath = saveLocation + fileName + fileExtension;
fuAvatar.SaveAs(savePath);
string imageDBPath = fileName + fileExtension;
LinqClass1DataContext dc = new LinqClass1DataContext();
int userid = Convert.ToInt32(Session["userid"]);
var tblUser = (from u in dc.Users
where u.userid == userid
select u).First();
tblUser.imagePath = #"\savedAvatars\"+imageDBPath;
dc.SubmitChanges();
lblResult.Text = "Avatar lastet opp!";
}
else lblResult.Text = "Avatar ikke lastet opp!";
}
And to load the picture:
public void GetUserAvatar()
{
int userid = Convert.ToInt32(Session["userid"]);
var varPath = dc.Users.Single(u => (u.userid == userid)).imagePath;
string imagePath = Convert.ToString(varPath);
imgAvatar.ImageUrl = imagePath;
}
you should add a generic handler file (.ashx) and write in it something like that:
string sql = "select image from table1";
SqlCommand command = new SqlCommand(sql, con);
SqlDataReader dReader = command.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Source"]);
dReader.Close();
then in your page do something like this:
img.ImageUrl = "Handler.ashx;
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129 read this article, first I've found. Basically you need to create a handler which responds with the raw image.
Please find the answer in below link.
Get images from database using Handler
You will have to create a handler which will load the image and u can pass the source to image
tag.

Categories