I'm doing an employee registration were there is an image that the user can preview the picture they choose. So my problem is, when I tried to preview the selected image, the filename in the fileupload is gone..
the "save-14-copy.png" is the filename of the picture.
So next step is to preview the image..
So as you can see the "save-14-copy.png" is already gone after hitting the button preview.
How can I retain the filename so I will not get an error when saving it.?
Code for design:
<asp:Button runat="server" ID="Button1" Text="PREVIEW" CssClass="button-green" OnClick="Button1_Click"/>
Javascript:
<script type="text/javascript">
function ImagePreview(Imagepath) {
if (Imagepath.files && Imagepath.files[0]) {
var Filerdr = new FileReader();
Filerdr.onload = function (e) {
document.getElementById("<%= hfImage.ClientID %>").value = e.target.result;
}
Filerdr.readAsDataURL(Imagepath.files[0]);
}
}
</script>
Codebehind:
protected void Button1_Click(object sender, EventArgs e)
{
EmpImage.ImageUrl = hfImage.Value;
}
i think you should save the file at preview-click and handle the filename there
protected void Button1_Click(object sender, EventArgs e)
{
hfImagename.Value = fuFile.PostedFile.FileName;
fuFile.PostedFile.SaveAs(#"C:\foo\" +fuFile.PostedFile.FileName);
}
Your Preview button is actually causing a post back to the server. The way you have it setup now, the Preview button would be more appropriately called Upload.
You are using the FileReader object in order to read the file from the user's local file system and showing it in the image before upload. All of that should take place only in the client. Once the user is happy with the selected picture, he can upload the picture to the server.
Here is a very simple sample that should get you started.
.aspx file
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="preview" runat="server" ImageUrl="~/Images/NotSelectedYet.jpg" />
<br />
<asp:FileUpload ID="pictureOfMe" runat="server" />
<input type="button" value="Preview" onclick="Preview();" />
<br />
<asp:Button ID="Upload" runat="server" Text="Upload file to server" OnClick="Upload_Clicked" />
</div>
</form>
<script type="text/javascript">
function Preview() {
var fileInput = document.getElementById('<%= pictureOfMe.ClientID %>');
var filePreview = document.getElementById('<%= preview.ClientID %>');
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function (e) {
filePreview.src = reader.result;
}
reader.readAsDataURL(file);
}
else {
alert('Not an image file!');
}
}
</script>
</body>
Here we have an image that is showing a default picture when first loaded. Then we have a file upload control that lets the user select a picture to upload. And we have an html input button that the user clicks on to preview the selected picture. When this button is clicked, it runs javascript code that uses the FileReader to load the file an show it in the image. Note that the preview button will not cause a post back to the server.
And we also have a server button that will post the page (including the selected picture) to the server with a server event handler declared.
.aspx.cs file
public partial class TestImagePreviewAndUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload_Clicked(object sender, EventArgs e)
{
if(pictureOfMe.PostedFile.FileName != string.Empty) {
byte[] uploadedBytes = pictureOfMe.FileBytes;
//save uploaded picture here
}
}
}
Here, in the Upload_Clicked method we check if a file was uploaded and gets the file content as a byte[]. Actuelly storing the file is left as an exercise...
Note: Sample javascript (with some modifications) from here
Related
I have a product page. I want to add my product to my database and I want also to update my product.
I have a problem with images.
When I insert the product everithing is ok.. In my aspx page I have this code:
<span>
<asp:FileUpload ID="files" runat="server" AllowMultiple="true" />
</span>
<div runat="server" id="previewImages"></div>
and when I save my product, in code behind I have this code:
string filenm = string.Empty;
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
if (uploadfile.ContentLength > 0)
{
string filename = uploadfile.FileName;
System.IO.Directory.CreateDirectory(Server.MapPath("immScarpe/" + txtStyle.Text));
file.SaveAs(Server.MapPath("immScarpe/" + txtStyle.Text + "/") + fileName);
//this is pseudo-code
INSERT INTO PRODUCT_IMM (IdProduct, Path) VALUES (Id, "immScarpe/" + txtStyle.Text + "/" + fileName)
}
}
Now, the problem is that I can EDIT the saved product. When I click the edit button for a product, I have to load all it's data and let the user modify them. Also the images.
the main question is: How can I load the saved images in asp:FileUpload control?
Another thing I would like to do is to show images previews...in insert and in edit.
An Example of what I want to do is the thing that amazon does
but, if it's possible with only one FileUpload with AllowMultiple = true
I am willing to use other technologies like javascript, jquery and Ajax if it's necessary
Show Images Preview - Insert
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowpImagePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#previewImage').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<asp:Image ID="previewImage" runat="server" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange="ShowpImagePreview(this);" />
Here is a very basic example as to how you can handle images after they have been send to the server. In this snippet the filename of the image is fixed, but it should be enough to give you push in the right direction.
protected void Page_Load(object sender, EventArgs e)
{
//check if the file exists and show
if (File.Exists(Server.MapPath("testImage.jpg")))
{
setImage("/testImage.jpg");
}
}
//upload a new image
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
FileUpload1.SaveAs(Server.MapPath("testImage.jpg"));
setImage("/testImage.jpg");
}
catch
{
//error writing file
}
}
}
//delete the image
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
File.Delete(Server.MapPath("testImage.jpg"));
LinkButton1.Visible = false;
Image1.Visible = false;
}
catch
{
//error deleteing file
}
}
//set the image and show the delete link
private void setImage(string image)
{
Image1.ImageUrl = "/testImage.jpg";
Image1.Visible = true;
LinkButton1.Visible = true;
}
ASPX
<asp:Image ID="Image1" runat="server" Visible="false" />
<br />
<asp:LinkButton ID="LinkButton1" runat="server" Visible="false" OnClick="LinkButton1_Click">Delete image</asp:LinkButton>
<br />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
For displaying images to GridView from disk
https://www.aspsnippets.com/Articles/Display-Images-in-GridView-Control-using-the-path-stored-in-SQL-Server-database.aspx
Now you have the images shown, you want to have some replace or delete functionality on the images. You need to convert your field on the GridView for image to Template Field. You can do this by clicking on the source view of your ASPX page and replacing your ImageField or BoundField (whichever field you used in displaying the image).
See the design of the GridView on the question:
How to display image inside gridview template field without using handler class?
The way to bind the image source is in the answers in that question.
To have a delete or replace functionality, you can include a LinkButton control inside your TemplateField below the tag that displays the image.
You can set the LinkButton's CommandName property to 'Delete' or 'Replace' then on your .vb or .cs file, find the 'RowCommand' event for your GridView.
It goes something like (pseudo code only)
Protected Sub GridView_RowCommand(ByVal sender As Object, ByVal e As System.GridViewCommandEventArgs) Handles GridView.RowCommand
If e.CommandName = 'Delete' Then
'Place your delete query for your image record on the database here..
'Place your delete file from disk code here..
End If
End Sub
More info on GridView RowCommand Event
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.110).aspx
I use ajaxToolkit:AjaxFileUpload. It works when the user clicked in the start upload button. I want to change it so when the file is selected or drag-and-dropped, the uploader starts uploading automatically. What should I do? my code is:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUploader" OnUploadComplete="AjaxFileUploader_UploadComplete" runat="server" />
protected void AjaxFileUploader_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
AjaxFileUploader.SaveAs(MapPath("~/UploadedFiles/" + e.FileName));
}
Let your Upload component to use the class "FileAttachmentUpload"
then use the below jQuery.
$(".FileAttachmentUpload").change(function () {
$(".FileAttachmentUpload .ajax__fileupload_uploadbutton").click();
});
$(".ajax__fileupload_dropzone").on('drop', function () {
$(".ajax__fileupload_uploadbutton").click();
});
Recently I have been developing web form application in ASP.NET (c#):
I have an Image control:
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
And FileUpload & Button control
<asp:FileUpload ID="avatarUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
When user click button then "Upload" code is executed (the image is sent to the database). Problem is that I like to display the image which the user selected in Avatar Image controller before the user clicks "desperate" button.
Is that possible to do this automatically?
With the help of File Api of HTML5 (Example: Using files from web applications) you can accomplish this easily. Change the markup to use input type="file" instead of asp:FileUpload and add ID, add tag runat="server" to make it accessible from server. Your markup should look like:
<input ID="avatarUpload" type="file" name="file" onchange="previewFile()" runat="server" />
<%--<asp:FileUpload ID="avatarUpload" runat="server" />--%>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
Now add a javascript function previewFile in the head of document:
<head runat="server">
<title></title>
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=Avatar.ClientID %>');
var file = document.querySelector('#<%=avatarUpload.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
</head>
Now after selecting an image you can see the preview like below:
You can use css to re-size it to a thumbnail.
After clicking the Upload button, in the code you can find the posted file:
protected void Upload(object sender, EventArgs e)
{
int contentLength = avatarUpload.PostedFile.ContentLength;//You may need it for validation
string contentType = avatarUpload.PostedFile.ContentType;//You may need it for validation
string fileName = avatarUpload.PostedFile.FileName;
avatarUpload.PostedFile.SaveAs(#"c:\test.tmp");//Or code to save in the DataBase.
}
I am trying to get the actual HTML text for the control from the client browser because some of the info in this control don't show on the sever side special the "Style". So How can get the whole HTML text for a control?
<asp:TextBox ID="tb1" runat="server" OnChange="tbOnChange();" />
<script type="text/javascript">
function tbOnChange() {
var tb1 = document.getElementById('tb1');
alert(tb1.value);
}
</script>
EDIT: For get style in C#
ASP page:
<input type="text" id="tb1" runat="server" style="color:Red;" />
C# page:
protected void Page_Load(object sender, EventArgs e)
{
var style = tb1.Style;
}
Regards
k.
I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.
In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)