Save images to folder in VB.net - asp.net

I am trying to save an image from the client side to a folder using vb.net
"" the image that has the myImage ID ""
<asp:Image runat="server" ID="myImage" ImageUrl="http://www.govcomm.harris.com/images/1F-81-imageLinks650a.jpg" />
<asp:Image runat="server" ID="myImage2" ImageUrl="http://www.govcomm.harris.com/images/2F-81-imageLinks650b.jpg" />
this is just the location where i want to save my image :
i haven't run or try any thing with this code , i am just wondering how to do this
this location is on the server side
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim saveLocation As String = Server.MapPath("PDFs")
End Sub
Also, I would like to know if there is a way to use the id to save since i might have more than one image to be saved.

Try this one.....
import System.Net
Dim filepath As String = Server.MapPath(myImage.ImageUrl)
Using client As New WebClient()
client.DownloadFile(filepath, Server.MapPath("Specify the path where you want to store+imagename")) //------For example client.DownloadFile(filepath,Server.MapPath("~/Image/282.gif"))
End Using

If you want to upload a file from the client side (from the user via browser) to the server folder, you need to user the FileUpload control
<asp:FileUpload ID="FileUpload1" runat="server" />
And in your Codebehind, you can save that to a location by Calling the PostedFile.SaveAs method
If FileUpload1.HasFile Then
somefileNameWithExtension="file.pdf" ' Replace this with a a valid file name
FileUpload1.PostedFile.SaveAs(somefileNameWithExtension)
End If
EDIT : As per the comment
If you want to download a file from the internet, you can do it with the WebClient classes DownloadFile method. Here is an example.
Using webClient As New WebClient()
Dim targrtFileName = "D:\\myfile.png" '
Dim sourceFile = "http://converter.telerik.com/App_Themes/images/ccHead.png"
'read the Source of your image control and replace in sourceFile variable.
webClient.DownloadFile(sourceFile , targrtFileName)
End Using

Related

How to check the file is already uploaded or not by using Ajax File Upload?

I am asking a question about Ajax File Upload again.. T_T
I have an ASP.NET webform (using VB.NET) which is using Ajax File Upload. I update my database table whenever I upload a file. I am checking a file is already uploaded or not when I drag into my upload panel and click the upload button.
If the target file is already uploaded, I want to show my error label like 'the file is already uploaded' . But the label doesn't showing . I did debug to trace the result and the file is really existing and it went through my label text setting but didn't show on my form.
Which part of my code is being wrong? I hope someone can guide me.
here is my asp code
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
//customize the drag panel
function AjaxFileUpload_change_text() {
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "Click Upload";
document.getElementsByClassName('ajax__fileupload_uploadbutton')[0].style.width = '100px';
}
</script>
<div style="width:40%;padding:25px;margin-left:200px">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" AllowedFileTypes="pdf" MaximumNumberOfFiles="10" />
<asp:Button ID="cmdDone" runat="server" Text="Done" style="display:none" ClientIDMode="Static" />
<script>
function MyCompleteAll() {
$('cmdDone').click()
}
</script>
</div>
<asp:Label ID="lblmsg" runat="server" Text="" Width ="150px" style="color:red"></asp:Label><br />
</asp:Content>
.vb code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "AjaxFileUpload_change_text();", True) //customize ajax panel
lblmsg.Text = "" //error display
End Sub
Protected Sub MyCompleteAll(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim filename As String = e.FileName.Split(".").First + "_" + fileupload + ".pdf"
Dim path As String = Server.MapPath("~/uploads/")
//to add a database table of files up-loaded.
Dim constr As String = CONN + g_schema
Using con As New MySqlConnection(constr)
con.Open()
'check file is already uploaded
Dim select_seq As String = "select fname from filetable where fname like '" +
e.FileName.Split(".").First + "%'"
Dim cmd As New MySqlCommand(select_seq, con)
Dim reader = cmd.ExecuteReader()
While reader.Read()
fname = reader(0).ToString
End While
con.Close()
//the file is already uploaded
If fname IsNot "" Then
lblmsg.Text = "Already uploaded. Please upload the other files."
Else
// Upload process code
End Sub
Thank you.
I going to suggest you check the file on the file upload done event.
So, we can THEN build up a list of files that exist - you have the possibility of more then one file up-load.
So, I suggest dropping in a text box to "hold" each bad (duplicate) file.
So, lets persist into session() the duplicate files (we can NOT use controls on the page in the 3 events (start, complete, complete all).
So, we have this code:
Dim DupList As New List(Of String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("DupList") = DupList
txtDups.Visible = False
Else
DupList = Session("DupList")
End If
End Sub
And say this markup - the text box, a grid view, and of course the FileUpload.
So, say this markup up:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
/>
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
<asp:TextBox ID="txtDups" runat="server" TextMode="MultiLine" Width="523px"></asp:TextBox>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table" DataKeyNames="ID"></asp:GridView>
</div>
So far - VERY good you have that JavaScript button click to get our VERY imporant and needed final post back when done.
So, a single file upload done event - looks like this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' now code to add say to a database table of files up-loaded.
' but FIRST CHECK if the file already exists
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now add to database
Dim NewRow As DataRow = rstFiles.NewRow
NewRow("FileName") = e.FileName
NewRow("UpLoadTime") = Date.Now
NewRow("User_id") = 1
NewRow("Size") = e.FileSize
NewRow("SavePath") = Path.GetDirectoryName(strFileSave) ' get path only
rstFiles.Rows.Add(NewRow)
MyRstUpdate(rstFiles, "MyUpLoadFiles")
End If
End Sub
So note in above HOW WE SKIP the file if it exists. And of course if it does exist, then we of course don't make an entry in the MyFilesUpLoad table.
Ok, so all files up-load - that js button click fires, and we now have this final code stub run:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
' this final code is triggered by the javascrpt "click" on
' all file uplaod done
' if there are some duplicates - dispay to user.
If DupList.Count > 0 Then
txtDups.Visible = True
For Each s As String In DupList
If txtDups.Text <> "" Then txtDups.Text &= vbCrLf
txtDups.Text &= s & " already exists - skipped and not uploaded"
Next
End If
' now addtonal code - maybe display gird of up-loaded files
Dim strSQL As String = "select * from MyUpLoadFiles where UpLoadTime >= #D"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#D", SqlDbType.DateTime).Value = Date.Today
Gfiles.DataSource = MyRstP(cmdSQL)
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
So, it will look like this:
We hit ok, and now we have/see this:
Ok, so now lets try to re-upload two files that exist.
We So, we will see this:
So, we persist that "bad" list, and skip/don't save the file in the complete event.
And here are the two data helper routines - I don't think it needs much suggesting that one gets VERY tired VERY fast by having to type over and over some simple code to get data into a table - so I used these two helper routines to save World poverty and a few keyboards
Public Function MyRstP(cmdSQL As SqlCommand) As DataTable
Dim rstData As New DataTable
Using cmdSQL
Using conn = New SqlConnection(My.Settings.TEST4)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rst As DataTable, strTable As String)
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT * from " & strTable, conn)
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
conn.Open()
da.Update(rst)
End Using
End Using
End Sub
Edit: Check for "confirmed" file
Follow up question was not only does the file exist, but at some point (or some how - not yet disclosed), the use has the means to check box, or change the status of the up-loaded files. And if file has not yet been confirmed, then we still allow up-loading.
So, the code in question would be this:
Dim strSQL As String = "SELECT * from MyUpLoadFiles where FileName = #F
AND Confirmed = 9"
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#F", SqlDbType.NVarChar).Value = e.FileName
Dim rstFiles As DataTable = MyRstP(cmdSQL)
If rstFiles.Rows.Count > 0 Then
' the file exists.
' file is confirmed - don't save, add to our already exist list
DupList.Add(e.FileName)
Session("DupList") = DupList
Else
' file is ok, new - save it - (or not confirmed)

How would I change a property of an image without knowing its ID?

I want to use the Sector variable that is sent to the SetSectorImage sub to name the image that is being changed (the images do already exist on the web form, I am only changing the URLs). A Google search only led me to an article on MSDN about the CallByName method but I don't know if it will work in this situation and of it will, I can't figure out how.
Here's the article if it helps: http://msdn.microsoft.com/en-us/library/22x2chfx.aspx
Imports System
Imports System.IO
Public Class Launcher
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SetSectorImage("Sector1")
SetSectorImage("Sector2")
SetSectorImage("Sector3")
End Sub
Sub SetSectorImage(Sector As String)
Dim SectorStatus As String
Try
Using Reader As New StreamReader(Sector + ".txt")
SectorStatus = Reader.ReadToEnd()
Reader.Close()
Sector_SHOULD_BE_USED_HERE.ImageUrl = ("~/Images/" + SectorStatus)
End Using
Catch ex As Exception
ErrorMessage.Text = ("There was an error reading the status of: " + Sector)
ErrorMessage.Visible = True
End Try
End Sub
End Class
Let's suppose you have Images on the page:
<asp:Image ID="Sector1" />
<asp:Image ID="Sector2" />
<asp:Image ID="Sector3" />
You can access them with Control.FindControl Method
Dim myControl1 As Control = FindControl(Sector)
Dim myImage As Image = myControl1
myImage.ImageUrl = ("~/Images/" + SectorStatus)
I did some more research on CallByName() and found that I can use it in this situation. The line to change the image URL would be:
CallByName(Sector, "ImageUrl", CallType.Set, "~/Images/" + SectorStatus)

VB.NET write to file

This should be an easy one, but I'm strugling.
I've developed a web page and I'm trying to load values into a text file. I have the asp webform with a textbox and a button. When the button is pressed loads the message from the textbox to the text file.
When debugg it, it appears to work, but I can not see anything written in the file when I open it (or maybe I'm looking in the wrong place?)
When I publish it, it does not work.
Here is the code I'm using
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
' Both file_name below seem to work
' Dim FILE_NAME As String = "TB.txt"
Dim FILE_NAME As String = "..\TB.txt"
Dim line1 As String
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'objWriter.NewLine = True
line1 = TextBox1.Text
objWriter.WriteLine(line1)
'objWriter.Write(TextBox1.Text)
objWriter.Close()
MsgBox("Text written to file")
End Sub
Any help will be much appreciated
Try this:
IO.File.WriteAllText(FILE_NAME, TextBox1.Text)
MSDN Documentation
I found that the problem was created by this line:
MsgBox("Text written to file")
Once this was removed all worked fine.
Thanks for all the advice and support

Deleting Dynamically Populated images from a Directory (NOT GridView) ASP.NET (VB)

The code below displays a thumbnail of each image in a specific server directory and when I click on the image it pops up a nice full sized picture. It works perfectly.
I would however, like to be able to delete an image. I first thought I could have a button at the bottom of the page with a checkbox next to each image, giving it a uniqueID as per the filename but as they are dynamically created I couldn’t figure how to handle the Click Event on the button for a randomly named Checkbox ID. Then I tried adding a button next to each item and then tried an OnClick & OnServerClick to call a Sub but this didn’t work either.
Any/All suggestions welcomed :)
Private Sub ImageList()
If Directory.Exists(Server.MapPath("JobImages\" & DBC_JOB_JobID.Text)) Then
Dim MySB As New StringBuilder
Dim dirInfo As New DirectoryInfo(Server.MapPath("JobImages\" & DBC_JOB_JobID.Text))
MySB.Append("<ul class=""clearfix"">")
MySB.AppendLine()
For Each File In dirInfo.GetFiles()
MySB.Append("<li><a rel=""jobpic"" href=""JobImages\" & DBC_JOB_JobID.Text & "\" & File.Name & """><img src=""JobImages\" & DBC_JOB_JobID.Text & "\Thumbs\" & File.Name & """ width=""150"" height=""100"" /> <span class=""size"">" & File.Name & " </span></a></li>")
MySB.AppendLine()
Next
MySB.Append("</ul>")
MySB.AppendLine()
lblMyPictures.Text = MySB.ToString
End If
End Sub
OK what Kendrick is talking about (basically) is using server side controls to keep track of which file to delete. What you are doing right now is dumping markup into a Label control, which on postback won't fire an event on the server side. However you can accomplish this easily with server side controls.
The basic idea is you use a container control such as a Panel and add each child control to it. Then you hook events to each row with data identifying that row (such as filename).
Markup:
<asp:Panel ID="pnlList" runat="server">
</asp:Panel>
Code-Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Directory.Exists(Server.MapPath("Files")) Then
Dim objDirInfo As New DirectoryInfo(Server.MapPath("Files"))
For Each objFile As FileInfo In objDirInfo.GetFiles()
Dim objLabel As New Label
objLabel.Text = objFile.Name
Dim objLinkButton As New LinkButton
objLinkButton.Text = "Delete"
objLinkButton.CommandName = "Delete"
objLinkButton.CommandArgument = objFile.Name
AddHandler objLinkButton.Command, AddressOf DeleteFile
Dim objLiteral As New LiteralControl
objLiteral.Text = "<br/>"
pnlList.Controls.Add(objLabel)
pnlList.Controls.Add(objLinkButton)
pnlList.Controls.Add(objLiteral)
Next
End If
End Sub
Public Sub DeleteFile(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
If e.CommandName = "Delete" Then
Dim strFileName As String = Server.MapPath("Files\" & e.CommandArgument)
If File.Exists(strFileName) Then
Dim objFile As New FileInfo(strFileName)
objFile.Delete()
End If
End If
End Sub
This would be an excellent example of where using a data aware would make your life a lot easier.
That said, if you didn't want to use a server-side control, you could assign an ID to each checkbox (i.e. DeleteImage_1) and then store the ID and associated image name in the viewstate on the page. Go through the checked checkboxes and refer back to the viewstate for the name that goes with each ID when they click the delete button.

Add script to page from user control .ASP.NET

how can i add a javascript file to the page head from a user control?
Thanks
use Page.RegisterStartupScript("pranay","javascriptFunction()")
put this thing in you load method of user control
check this out :
http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx
Are you using master page in your site? If yes then you should do all such includes in the master page. But then also you might face issue with the path of javascript file. You can include the file in following way:
<script type="text/javascript" language="javascript" src="<%= this.ResolveClientUrl("~/Script/jquery.js") %>"></script>
If you want to do it from User Control. Try the following:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Define the name, type and url of the client script on the page.
Dim csname As String = "ButtonClickScript"
Dim csurl As String = "~/script_include.js"
Dim cstype As Type = Me.GetType()
' Get a ClientScriptManager reference from the Page class.
Dim cs As ClientScriptManager = Page.ClientScript
' Check to see if the include script is already registered.
If (Not cs.IsClientScriptIncludeRegistered(cstype, csname)) Then
cs.RegisterClientScriptInclude(cstype, csname, ResolveClientUrl(csurl))
End If
End Sub

Resources