Using fileupload in listview edittemplate asp.net - asp.net

In a ListView edittemplate, I need to allow the user to replace an image. When the form is submitted for updating how can I determine if the user is uploading a new image and get that file info?
Thanks,
James

You could try something like this if you want to compare file size. Granted file size comparison is not the best but FileInfo has lots of other attributes you should be able to use to make sure.
FileInfo oldFileInfo; // get old file's fileInfo
var tempPath = "some-temp-path-";
var tempFile = String.Format("{0}\{1}", tempPath, FileUpload1.FileName);
FileUpload1.SaveAs(tempFile);
FileInfo tempFileInfo = new FileInfo(tempFile);
if(tempFileInfo.Length == oldFileInfo.Length)
{
// ask to upload a different image
}
else
{
// do other stuff
}

Grab the name off of the FileUpload.PostedFile.

Related

Xamarin - CachedImage - Access the downloaded file

I am using the CachedImage component of ffimageloading. I have a kind of gallery with a carousel view.
All the images are loaded through an internet URL, they are not local images. I would like to add the image sharing function. But I don't want to download the file again, I would like to know if there is a way to access the file that the CachedImage component already downloaded to be able to reuse it in the share function.
try using MD5Helper
var path = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey")'
Thanks Jason
I share with you how part of my code is:
var key = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey");
var imagePath = await ImageService.Instance.Config.DiskCache.GetFilePathAsync(key);
var tempFile = Path.Combine(Path.GetTempPath(), "test.jpg");
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
File.Copy(imagePath, tempFile);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Test",
File = new ShareFile(tempFile)
});
The temporary file I believe, since the cached file has no extension and the applications do not recognize the type.

How to find filebytes of individual uploaded files in asp.net?

I am implementing the multiple file upload through asp.net fileupload control & saving uploaded files to database. While iterating the files, I am trying to set the Data property of File class. For single file, I can set it as File.Data = postedFile.FileBytes.
But, while iterating files, FileBytes property value getting set everytime similar.
Can anybody explain what could be the reason? How can I implement it?
code sample:
if (fuAttachment.HasFiles)
{
foreach (HttpPostedFile postedFile in fuAttachment.PostedFiles)
{
DataAccess.File file = new DataAccess.File();
file.Data = fuAttachment.FileBytes;//not working for multiple files.
}
}
Remember, a file upload control still posts files behind the scenes.
here is basically how to retrieve multiple files, this works with one and/or multiple file upload controls, and counts ALL the posted files in ALL of the upload controls:
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
try
{
if (userPostedFile.ContentLength > 0)
{
//do stuff with your file, check the attributes and functions of 'userPostedFile' to see what you can get from it, there is an input stream as well as file name among everything else.
}
}
catch (Exception Ex)
{
//here do stuff if file upload fails, adjust exception type as needed.
}
}

ASP.NET C# Handling an Image

Similar to one of my other questions, but I need clarification.
I have a web application where multiple users will be on at the same time. In the app, an image, which is in one of the app folders, will be drawn on like below, saved, and then added to the image control on the page.
Bitmap image = new Bitmap(Server.MapPath("~") + "/Assets/img/timegrid.jpg");
Graphics graphics = Graphics.FromImage(image);
Pen p = new Pen(Color.Blue, 5);
//draw on image
graphics.DrawLine(p, aPoint, bPoint);
//save new image
image.Save(Server.MapPath("~") + "/Assets/img/newtimegrid.jpg");
imgGrid.ImageUrl = "~/Assets/img/newtimegrid.jpg";
Each user's new image will look different. However, I'm worried that User A will see User B's newtimegrid.jpg instead of his own since every user is saving to the same filename. I've heard of using a generic Image Handler and I've read some of the solutions here, but I still don't understand how to use it, or how to call it if I made one, or if this is even a solution to my problem. Any help would be appreciated.
I would suggest you to keep userID in the session and use this id in the path to uniquely identifying the path of image for each user image path.
You can first check if path already exists for user.
string strDirPath = Server.MapPath("~") + "/Assets/img/ + Session["UserID"].ToString();
if(Directory.Exists(strDirPath))
{
Bitmap image = new Bitmap(strDirPath + "\\" + timegrid.jpg");
//your code here
}
else
{
DirectoryInfo CreateDirectory(strDirPath);
Bitmap image = new Bitmap(strDirPath + "\\" + timegrid.jpg");
//your code here
}

Deleting file after upload

I am trying to upload a file with the FileUpload control. When file is uploaded, I extract information from it and then i want to delete it.
I manage to upload it, save it and get the info from it, but when i try to delete it i get the follwing exception
"The process cannot access the file 'D:\IIS**OMITTED***\V75 personal ny.csv' because it is being used by another process.
string fn = Path.GetFileName(fu.PostedFile.FileName);
string SaveLocation = Server.MapPath("UploadedCSVFiles") + "\\" + fn;
FileInfo fi = new FileInfo(SaveLocation);
fu.PostedFile.SaveAs(SaveLocation);
fu.PostedFile.InputStream.Dispose();
DataTable dt = AMethodThatUsesFile(SaveLocation);
fi.Delete();
Try this code to delete file.
System.IO.File.Delete(SaveLocation );
You specified a method AMethodThatUsesFile(SaveLocation);. If it uses any classes like StreamReader to read file, please close the reader using StreamReader.Close(); method before trying to delete
dispose the fi before deleting. and then us File.Delete(). remember to use using statements when use disposable objects, or dispose it after use.
using System.io
File.Delete(Server.MapPath("../Nurturing/" + fnevents));
FileInfo fInfoEvent;
fInfoEvent = new FileInfo(fnevents);
fInfoEvent.Delete();
here fnevents is the name of the file that u are deleting. Nurturing is the name of the folder.

how to make a picture file downloadable?

I have an ASP.NET MVC3 application and I want to link_to an image file (png, jpeg, gif, etc), and when user clicks on it, the file goes to download, instead of the browser shows it; is there any way to do this?
take your link something like this:
#Html.ActionLink(
"Download Image", // text to show
"Download", // action name
["DownloadManager", // if need, controller]
new { filename = "my-image", fileext = "jpeg" } // file-name and extension
)
and action-method is here:
public FilePathResult Download(string filename, string fileext) {
var basePath = Server.MapPath("~/Contents/Images/");
var fullPath = System.IO.Path.Combine(
basePath, string.Concat(filename.Trim(), '.', fileext.Trim()));
var contentType = GetContentType(fileext);
// The file name to use in the file-download dialog box that is displayed in the browser.
var downloadName = "one-name-for-client-file." + fileext;
return File(fullPath, contentType, downloadName);
}
private string GetContentType(string fileext) {
switch (fileext) {
case "jpg":
case "jpe":
case "jpeg": return "image/jpeg";
case "png": return "image/x-png";
case "gif": return "image/gif";
default: throw new NotSupportedException();
}
}
UPDATE:
in fact, when a file is sending to a browser, this key/value will be generated in http-header:
Content-Disposition: attachment; filename=file-client-name.ext
which file-client-name.ext is the name.extension that you want the file save-as it on client system; for example, if you want to do this in ASP.NET (none mvc), you can create a HttpHandler, write the file-stream to Response, and just add the above key/value to the http-header:
Response.Headers.Add("Content-Disposition", "attachment; filename=" + "file-client-name.ext");
just this, enjoy :D
Well technically your browser is downloading it.
I don't think you can directly link to an image, and have the browser prompt to download.
You could try something where instead of linking directly to the image, you link to a page, which serves up the image in a zip file perhaps - which of course would prompt the download to occur.
Yes, you can.
Now, you'll need to customize this to suit your needs, but I created a FileController that returned files by an identifier (you can easily return by name).
public class FileController : Controller
{
public ActionResult Download(string name)
{
// check the existence of the filename, and load it in to memory
byte[] data = SomeFunctionToReadTheFile(name);
FileContentResult result = new FileContentResult(data, "image/jpg"); // or whatever it is
return result;
}
}
Now, how you read that file or where you get it from is up to you. I then created a route like this:
routes.MapRoute(null, "files/{name}", new { controller = "File", action = "Download"});
My database has a map of identifiers to files (it's actually more complex than this, but I am omitting that logic for brevity), I can write urls like:
"~/files/somefile"
And the relevant file is downloaded.
I don't think this is possible but a simple message saying right click to save image would suffice I think.

Resources