Using this on an ASPX page using ASP.net 4.0
<input type="file" id="File1" name="myfiles" multiple="multiple" runat="server">
I want something like this in VB code
For Each File in File1
File1.PostedFile.SaveAs(savePath & File1.Value)
However, I can't figure out the syntax for that to work. Googling results only in jquery plugins and scripts, and I don't want all that if I could just get it to work with what I have already.
Any ideas?
yes it is more simple take a look here :
<td>
<asp:FileUpload runat="server" ID="FileUpload1" AllowMultiple="true" name="files[]" onchange="handleFileSelect(this)" />
<asp:HiddenField runat="server" ID="filesToIgnore" />
<div style="float:right;">
<asp:Button runat="server" ID="btnAddSubArticle" Text="Aggiungi" />
</div>
</td>
then javascript to your stuff in example from muy previous project:
<!-- The necessary scripts that do work son. -->
<script type='text/javascript'>
function handleFileSelect(evt) {
// FileList object
//var files = evt.target.files;
var files = evt.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) { continue; }
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.id = "span-img";
// Creates a thumbnail with an onclick function that will handle the mock deletion
span.innerHTML = ['<img data-id="img' + new Date().getTime() + '" class="thumb" src="', e.target.result,
'"title="', escape(theFile.name), '"onclick="deleteImage(this);" />'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
//The image was clicked delete it
function deleteImage(imgToDelete) {
try {
var fu = document.getElementById('<%=filesToIgnore.ClientID.ToString%>')
fu.value += (imgToDelete.title + ",");
imgToDelete.style.display = 'none';
}
catch (err)
{ alert(err); }
}
</script>
Then server side(there's a little bit more code for some stuff in here take a look into this and modify it as per your need)
Dim NewLine As String = "<br/>"
Dim ListFiles As New List(Of String)
Dim ignoredFiles As String() = filesToIgnore.Value.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
For Each el In FileUpload1.PostedFiles
If Not ignoredFiles.Any(Function(x) el.FileName.Contains(x)) Then
Select Case Path.GetExtension(el.FileName.ToString.ToLower)
Case ".jpg", ".png", ".jpeg", ".tiff", ".bmp", ".gif"
Try
Dim P As String = Server.MapPath("~/App_Data/temp/img/") & el.FileName.ToString
el.SaveAs(P)
Dim F As New FileInfo(P)
'Dim NewName As String = Guid.NewGuid.ToString & F.Extension.ToString
'ListFiles.Add(NewName)
'*****************************AZIONI DI RIDIMENSIONAMENTO E WATERMARK*******************************'
' Dim img As New Bitmap(P)
Dim imgResizer As New ProtectedImage(Server.MapPath("~/App_Data/temp/img/"), P, Server.MapPath("~/App_Data/temp/img/th/"), Server.MapPath("~/App_Data/temp/img/w/watermark.png"), Server.MapPath("~/App_Data/temp/img/w/watermark.png"), 400, 400, 80, True, GetNumber, ddlDomainMicroArticle.SelectedItem.ToString)
imgResizer.GenerateImages()
If imgResizer.StateWork = ProtectedImage.workState.WorkCompleted Then
lbl.Text = "Watermark e Resize completati" & NewLine
Else
lbl.Text = "Errore durante l'elaborazione dell'immagine" & NewLine
End If
'*****************************AZIONI DI RIDIMENSIONAMENTO E WATERMARK*******************************'
Dim ResizedImage As String = imgResizer.FileList.Item(1).ToString
Dim Thumbnails As String = imgResizer.FileList.Item(2).ToString
ListFiles.Add(ResizedImage)
ListFiles.Add(Thumbnails)
If MoveToCDN(ResizedImage, Thumbnails) Then
lbl.Text = lbl.Text & el.FileName & " Caricata" & NewLine
Else
lbl.Text = lbl.Text & el.FileName & " Fallita" & NewLine
End If
imgResizer.Dispose()
' Elimina l 'eventuale watermark se esiste
If File.Exists(Server.MapPath("~/App_Data/temp/img/w/watermark.png")) Then
File.Delete(Server.MapPath("~/App_Data/temp/img/w/watermark.png"))
End If
If File.Exists(Server.MapPath("~/App_Data/temp/img/" & Replace(ResizedImage, "rs_", ""))) Then
File.Delete(Server.MapPath("~/App_Data/temp/img/" & Replace(ResizedImage, "rs_", "")))
End If
If File.Exists(Server.MapPath("~/App_Data/temp/img/th/" & Replace(Thumbnails, "th_", ""))) Then
File.Delete(Server.MapPath("~/App_Data/temp/img/th/" & Replace(Thumbnails, "th_", "")))
End If
If File.Exists(P) Then
File.Delete(P)
End If
Catch ex As Exception
lbl.Text = lbl.Text & ex.Message & NewLine
End Try
Case Else
lbl.Text = lbl.Text & el.FileName.ToString & " Estensione file non consentita" & NewLine
End Select
End If
Next
I hope that is usefully
This is actually a pretty simple thing to do.
ASP.NET 4.0- Method..
Your HTML markup for your file uploader should read as:
<input type="file" multiple="multiple" id="file1" runat="server" />
When your code is submitted, you can access the posted files using the following logic:
Dim f As HttpPostedFile
For i As UInt16 = 0 To Request.Files.Count - 1
f = Request.Files(i)
'Your logic here....
Next
ASP.NET 4.5+ Method...
Your HTML markup for your file uploader should read as:
<asp:FileUpload ID="file1" runat="server" AllowMultiple="true" />
Then, when your form is submitted, just use code similar to:
For Each f In file1.PostedFiles
'Your logic here..
Next
That logic will allow you to iterate through each file uploaded via the control. Each "PostedFile" is of type "HttpPostedFile", which will give you all sorts of properties on the name, content length, extension and filebytes.
Hope this helps, welcome to StackOverflow!
Related
I am working on various bug fixes on a small website and one thing is really confusing me.
Is there an easy explanation as to why some pages will redirect to a login page instead of the actual destination... but only while using Chrome?
Example: This page is supposed to check input against our mailing list and either add the details or return a message saying they're already on the list. It works fine in IE (go figure) but when I try it in Chrome it redirects me to the account login page.
HTML:
<%# Page Language="VB" MasterPageFile="~/Standard-no-menu.master" AutoEventWireup="false" CodeFile="join-email.aspx.vb" Inherits="JoinEmail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<style type="text/css"><!-- #import url("/update-details.css"); --></style>
<script type="text/javascript" language="javascript" src="js/JScript.js"> </script>
<script language="javascript" type="text/javascript">
function validateForm()
{
if (aForgotPwd.style.display != null && aForgotPwd.style.display.toString() != "none") {
var emailEle = document.getElementById("<%= txtEmail.ClientID %>");
emailEle.focus();
return false;
}
if(document.getElementById('<%= txtEmail.ClientID %>').value=="")
{
alert("Please enter a value in the field \"Email\".");
document.getElementById('<%= txtEmail.ClientID %>').focus();
return (false);
}
validemail=0;
var checkStr = document.getElementById('<%= txtEmail.ClientID %>').value;
for (i = 0; i < checkStr.length; i++)
{
if(checkStr.charAt(i)=="#")
validemail |= 1;
if(checkStr.charAt(i)==".")
validemail |= 2;
}
if(validemail != 3)
{
alert("Please enter a valid email address.");
document.getElementById('<%= txtEmail.ClientID %>').focus();
return (false);
}
if(document.getElementById('<%= txtFirstName.ClientID %>').value=="")
{
alert("Please enter a value in the field \"First Name\".");
document.getElementById('<%= txtFirstName.ClientID %>').focus();
return (false);
}
if(document.getElementById('<%= txtLastName.ClientID %>').value=="")
{
alert("Please enter a value in the field \"Last Name\".");
document.getElementById('<%= txtLastName.ClientID %>').focus();
return (false);
}
}
</script>
<h1>Join Global PC Mailing List
</h1>
<div class="update-message"><asp:Label ID="lblMessage" runat="Server"></asp:Label></div>
<asp:Panel ID="pnlCreateAccount" runat="server">
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">Email Address:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" ID="txtEmail" MaxLength="255" width="350" runat="server"></asp:TextBox><b><a id="aForgotPwd" href="/forgotten-password.aspx" style="display:none"> Forgot password?</a></b></div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label"> </div>
<div class="update-field">We will never give your email address to anyone. Read our <a runat="server" href="~/privacy.aspx">privacy policy</a></div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label">Company Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtAccountName" ID="txtAccountName" MaxLength="40" width="350" runat="server"></asp:TextBox>
</div>
</div>
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">First Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtFirstName" ID="txtFirstName" MaxLength="255" width="350" runat="server"></asp:TextBox></div>
</div>
<div class="update-row">
<div class="update-mandatory">*</div>
<div class="update-label">Last Name:</div>
<div class="update-field"><asp:TextBox cssClass="textbox" name="txtLastName" ID="txtLastName" MaxLength="255" width="350" runat="server"></asp:TextBox></div>
</div>
<h1>Choose Your Email Subscriptions</h1>
<div class="update-row">
<div style="float:left">
<div class="update-mandatory"> </div>
<div class="update-label">Subscribe to General Newsletters:</div>
<div class="update-checkbox"><asp:CheckBox ID="chkGenernalNewsletters" runat="server"></asp:CheckBox></div>
</div>
</div>
<div class="update-row">
<div class="update-mandatory"> </div>
<div class="update-label"> </div>
<div class="update-field">
<div class="green-button">
<asp:LinkButton ID="btnRegister" OnClientClick="return validateForm();" AlternateText="Join Up" Text="Join Up" runat="server" />
</div>
</div>
</div>
</asp:Panel>
</asp:Content>
VB.NET
Imports DataAccessLayer
Imports System.Data
Imports System.Net
Imports System.Net.Mail
Imports com.verticalresponse.api
Partial Class JoinEmail
Inherits System.Web.UI.Page
Dim c As GPCUser
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Master.Page.Title += " | Register"
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
'Response.Redirect("update-details.aspx")
Else
c = New GPCUser
End If
If c.AccountNo = 0 Or c.AccountNo = CInt(System.Configuration.ConfigurationManager.AppSettings("WebsiteAccount")) Then
Else
Response.Redirect("update-details.aspx")
Exit Sub
End If
If Not Page.IsPostBack Then
Dim dt As DataTable = Nothing
dt = SqlHelper.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings("dbConn"), "x_ww_spGetCustomer", Request("custID")).Tables(0)
If Not dt Is Nothing Then
If dt.Rows.Count > 0 Then
Dim dr As DataRow = dt.Rows(0)
txtAccountName.Text = dr("AccountName")
txtFirstName.Text = dr("FirstName")
txtLastName.Text = dr("LastName")
txtEmail.Text = dr("Email")
If Request("custID") > 0 Then
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(Request("custID"))
' chkComputerPromotions.Checked = subscriptions.IsComputerPromotions
'chkElectronicPromotions.Checked = subscriptions.IsElectronicPromotions
chkGenernalNewsletters.Checked = subscriptions.IsGenernalNewsletters
End If
End If
End If
End If
End Sub
Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRegister.Click
' c.CreateCustomerDetails(txtAccountName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtAddress.Text, txtSuburb.Text, txtCityTown.Text, txtPostcode.Text, txtPhone.Text, txtMobile.Text, lstCountry.SelectedValue)
' c.GeneratedPassword = txtPassword.Text
' GPCUser.AddUpdateCustomer(c)
' ' Save the subscription details
'
'If Request("custID") > 0 and Request("AccNO") > 0 Then
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(Request("custID"))
'subscriptions.IsComputerPromotions = chkComputerPromotions.Checked
'subscriptions.IsElectronicPromotions = chkElectronicPromotions.Checked
subscriptions.IsGenernalNewsletters = chkGenernalNewsletters.Checked
subscriptions.Save()
'End IF
' Session("Customer") = c
'SendUpdateAccountEmailMessage(c.EmailCount)
'ClientScript.RegisterClientScriptBlock(Me.GetType(), "Thanks", "alert('Your Website PC account has been created. ');", False)
If chkGenernalNewsletters.Checked = True Then
Dim listID As Integer = 284662333
Dim isMember As Boolean = False
Dim newSession As New loginArgs()
newSession.username = "Not Relevant"
' Your VerticalResponse username
newSession.password = "Not Relevant"
'Your VerticalResponse password
' objLA.impersonate_user = "subaccount#emailaddress.com"; // If accessing or acting as a subaccount, uncomment this and replace it with the applicable email address.
newSession.session_duration_minutes = "120"
Dim [date] As DateTime = DateTime.Now
' This is generated by creating a Service Reference that points to the VerticalResponse WSDL.
Dim VRUser As New VRAPI()
' Let's try to log in. The login call will return a session ID, which we will use in all subsequent calls.
Dim sessionId As String = Nothing
Try
sessionId = VRUser.login(newSession)
Catch ex As System.Exception
lblMessage.Text = ex.ToString()
End Try
Dim getMember As New getListMemberByEmailAddressArgs()
getMember.session_id = sessionId
getMember.list_id = listID
getMember.email_address = txtEmail.Text
Try
VRUser.getListMemberByEmailAddress(getMember)
isMember = True
Catch ex As System.Exception
isMember = False
End Try
If (isMember = False) Then
Dim nMember As New ListMember()
nMember.list_id = listID
Dim memberData As NVPair() = New NVPair(2) {}
memberData(0) = New NVPair()
memberData(0).name = "email_address"
memberData(0).value = txtEmail.Text
memberData(1) = New NVPair()
memberData(1).name = "first_name"
memberData(1).value = txtFirstName.Text
memberData(2) = New NVPair()
memberData(2).name = "last_name"
memberData(2).value = txtLastName.Text
nMember.member_data = memberData
Dim objAL As New addListMemberArgs()
objAL.list_member = nMember
objAL.session_id = sessionId
Try
VRUser.addListMember(objAL)
Catch ex As System.Exception
txtEmail.Text = ex.ToString()
End Try
Else
pnlCreateAccount.Visible = False
lblMessage.Text = "You are already on our mailing list."
Exit Sub
End If
End If
pnlCreateAccount.Visible = False
lblMessage.Text = "you have successfully subscribed to Website PC email database."
End Sub
<System.Web.Services.WebMethod()> _
Public Shared Function ValidateEmail(email As String) As String
Dim wbClient As WebClient = New WebClient()
Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
Dim reqHTML As Byte()
reqHTML = wbClient.DownloadData(strUrl)
Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
Dim output As String = objUTF8.GetString(reqHTML)
If String.IsNullOrEmpty(output) Then Return String.Empty
Return output
End Function
Private Sub SendMessage(fromEmail As String, fromEmailName As String, _
toEmails As String(), IsBodyHtml As Boolean, message As String, subject As String)
Dim mail As MailMessage = New MailMessage
mail.From = New MailAddress(fromEmail, fromEmailName)
For Each toEmail As String In toEmails
mail.To.Add(New MailAddress(toEmail))
Next
mail.Bcc.Add(fromEmail)
mail.IsBodyHtml = IsBodyHtml
mail.Subject = subject
mail.Body = message
Dim s As New SmtpClient(System.Configuration.ConfigurationManager.AppSettings("MailServer"))
s.Send(mail)
End Sub
Private Sub SendUpdateAccountEmailMessage(emailCount As Integer)
Dim subject As String = "ALERT : Website user subscribed to email database"
Dim message As String
message &= "Via page join-email" & vbCrLf & vbCrLf
message += "Account No: " & Request("custID") & vbCrLf
message += "Email : " & txtEmail.Text & vbCrLf
message += "Account Name : " & txtAccountName.Text & vbCrLf
message += "First Name : " & txtFirstName.Text & vbCrLf
message += "Last Name : " & txtLastName.Text & vbCrLf
message += "Email : " & txtEmail.Text & vbCrLf
message += "Subscribe to General Newsletters : " & chkGenernalNewsletters.Checked & vbCrLf
'message += "Subscribe to Computer Promotions: : " & chkComputerPromotions.Checked & vbCrLf
'message += "Subscribe to Electronic Promotions: : " & chkElectronicPromotions.Checked & vbCrLf
message &= vbCrLf & vbCrLf
message += "Regards" & vbCrLf & vbCrLf & "WebsitePC Admin Team"
SendMessage(ConfigurationManager.AppSettings("AccountDetailsUpdateEmail"), "Website PC", _
New String() {ConfigurationManager.AppSettings("AccountDetailsUpdateEmail")}, False, message, subject)
End Sub
End Class
I want to create a file on my server, and then, write datas in
<script runat="server" language="VBScript">
Function saveData()
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("ecr.txt", 8,true)
f.WriteLine("osgfouds")
End Function
</script>
I get an error in my browser telling me 'object required: server' at the 'Server.CreateObject' line
Server.createobject would be for VBScript/ASP scripts on the server itself. The client browser would not be able to support Server for this reason.
As an added note. You need to Close out your file object(f) because it will keep the file open and cause errors when you try to write to it again. Also, I added the ForAppending bit so that you can specify it in your fso.opentextfile.
So to fix your script:
<script runat="server" language="VBScript">
Function saveData()
Const ForReading As String = 1
Const ForWriting As String = 2
Const ForAppending As String = 8
Dim fso as Object
Dim f as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("ecr.txt", ForAppending, true)
f.WriteLine("osgfouds")
f.Close
End Function
</script>
EDIT
This is an updated question from -> Here
EDIT
Ok, looking at your previous question and this one. Here's the thing: ASP runs at the server level and Loads vbscript into the website interface. Vbscript attached directly to ASP will run at the server level:
e.g.
<%
Const ForAppending = 8
dim fn,fp,fpn,wl,fulltext : fn = replace(formatdatetime(Now, 2), "/", "-") & ".txt"
Dim fso, msg : fp = "C:\Users\...\Desktop\Logs\"
fpn = fp & fn
dim sep : sep = "==========================================================================="&vbcrlf
dim ssep : ssep = vbcrlf & "--------------------------------------"
fso = CreateObject("Scripting.FileSystemObject")
dim IPAddress, HostName, LUname
IPAddress = Request.ServerVariables("remote_addr")
If (fso.FileExists("C:\Users\...\Desktop\Logs\" & fn)) Then
dim inSession,newuser
wl = fso.OpenTextFile(fpn, ForAppending, True)
inSession = fso.OpenTextFile("C:\Users\...\Desktop\Logs\" & fn, 1)
fulltext = inSession.ReadAll
'.....Code continues'
%>
So if your trying to activate a click event and attach it to a VBScript to write to a file on the server end, this will not work, because the vbscript will attempt to write it to the client regardless.
The proper way for a asp/vbscript to be designed for user entry updates needs to be executed in the following fashion:
BROWSER - click -> request to server -> server processes request -> serves new page -> BROWSER
Evidence provided -> Here
However, you can still utilize an XMLHTTPRequest or Ajax/Javascript to activate a script. Actually, funny thing is, I just asked about how to execute a very basic script like this recently. So here's how to do it:
You have your HTML file(whatever.html):
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type ="text/javascript" >
$(function () {
$("#button").click(function () {
$.get("test2.aspx", {
loadData: "John"
})
.done(function (data) {
if (data === "Fail") {
alert("Logging Failed!");
} else {
alert("Logged Success!");
}
})
.fail(function () {
alert("error");
});
});
});
</script>
</head><body>
<input type="button" id="button" value="Ecriture"></body>
And you have your ASPX File (test2.aspx):
<%# Page Language="VB" %>
<%
Dim LogData As String : LogData = Request.Params("loadData")
Dim SaveFile As String
Const ForReading As Integer = 1
Const StorageDirectory = "C:\Users\...\Desktop\Logs\serverlog.txt"
Const ForWriting As Integer = 2
Const ForAppending As Integer = 8
If Len(LogData) = 0 Then LogData = "{EMPTY STRING}"
Dim fso As Object
Dim f As Object
fso = CreateObject("Scripting.FileSystemObject")
f = fso.OpenTextFile(StorageDirectory, ForAppending, True)
f.WriteLine("New Entry:" & LogData)
f.Close()
If Err.Number <> 0 Then
SaveFile = "Fail"
Else
SaveFile = "Success"
End If
Response.Write(SaveFile)
%>
NOTE
The StorageDirectory must be a shared network folder so that the server can maintain updating the file.
I've tested this code and it works. Good Luck
This will work in VB.NET. Try this
Dim oFs
Dim vSharePath
Dim vFolder
Dim vPath
Dim objTStream
vSharePath = ConfigurationManager.AppSettings("NetworkPath").ToString
vFolder = Year(Date.Now) & Month(Date.Now).ToString & Date.Now.Hour.ToString & Date.Now.Second.ToString
vPath = vSharePath & "\" & vFolder
oFs = Server.CreateObject("Scripting.FileSystemObject")
If Not (oFs.FolderExists(vPath)) Then
Call oFs.CreateFolder(vPath)
objTStream = oFs.CreateTextFile(vPath & "\test.txt", True)
'Write some text to the file
objTStream.WriteLine("Hello World!")
objTStream.WriteLine()
objTStream.WriteLine("This is my first text file!")
'Close the TextStream object
objTStream.Close()
'Free up resources
objTStream = Nothing
End If
oFs = Nothing
http://webcheatsheet.com/asp/filesystemobject_object.php
I'm try to show images from database in a client side, but, I have been using many kinds of examples that I found and none work, none of the images shown. The last example I saw it's this:
http://www.codeproject.com/Tips/445876/Auto-bind-byte-to-asp-Image
I understand perfectly the example, but the images are still not displayed.
Someone help me a bit with this issue?
In summary, I'm use a HTML5 drag & drop files. Send the files via XMLHttpRequest in a FormData object. One handler take this files in byte() and store in SQL DataBase.
Client code:
$("#btnUploadFile").click(function () {
if (files.length <= 0) {
alert("Debe seleccionar algún fichero para subirlo.");
} else {
var expID = $("#ContentPlaceHolder1_hfExpId").val();
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
formData.append('file', files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', "FileHandler.ashx", true);
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr.setRequestHeader("ExpedienteID", expID);
xhr.onload = function () {
if (xhr.status === 200) {
RefreshFilePanel();
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
};
Handle code:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim documentBytes As Byte()
Dim lExpId As String = context.Request.Headers("ExpedienteID")
Dim fLenght As Integer
If (context.Request.Files.Count > 0) Then
Dim files As HttpFileCollection = context.Request.Files
For i = 0 To files.Count - 1
fLenght = files(i).ContentLength
documentBytes = New Byte(fLenght - 1) {}
context.Request.InputStream.Read(documentBytes, 0, fLenght)
UploadDocumentBy_ExpID(documentBytes, files(i).FileName, "Description" & lExpId.ToString, lExpId)
Next
End If
End Sub
More late, I try to put this byte() in a image tag on grid.
aspx code:
<asp:GridView ID="grdDocumentoByExp" runat="server" AutoGenerateColumns="false" Width="250px" DataSourceID="dtsDocumentByExpId">
<Columns>
<asp:BoundField DataField="Archivo" HeaderText="Archivo" />
<asp:BoundField DataField="docId" HeaderText="docId" />
<asp:BoundField DataField="Documento" HeaderText="Documento" Visible="false" />
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image
ID="imgThumb"
runat="server"
ImageUrl='<%# GetImage(Eval("Documento")) %>'
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
And the function GetImage in codebehind:
Public Function GetImage(image As Object) As String
Return "data:image/gif;base64," & Convert.ToBase64String(DirectCast(image, [Byte]()))
End Function
In all steps, there is no error, but I think that the error is posible located in the byte() file format..but i'm not sure.
Someone help me?
Sorry for my inglish and Thanks.
The problem is in how you read the file:
context.Request.InputStream.Read(documentBytes, 0, fLenght)
The Read method returns the number of bytes read, which can be less than the number of bytes that you request. You have to loop until you have got all bytes:
Dim offset as Integer = 0
Dim len as Integer
Do While offset < fLength
len = context.Request.InputStream.Read(documentBytes, offset, fLenght - offset)
offset += len
Loop
Using this ASP.Net LoginView, we would like to set focus on the User Name TextBox when it's loaded on the web page:
<asp:LoginView
ID="loginViewMain"
runat="server">
<LoggedInTemplate>
<asp:LoginName
ID="loginName"
runat="server"
FormatString="Hello, {0}!<br/><br/> You have successfully<br/> logged onto the staff site." />
<br/>
<br/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<br/>
<br/>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus
ID="loginStatus"
runat="server" />
</AnonymousTemplate>
</asp:LoginView>
This is the code-behind we tried to use to get focus on the User Name TextBox:
Private Sub loginViewMain_Load(sender As Object, e As EventArgs) Handles loginViewMain.Load
Dim objContentPlaceHolder As ContentPlaceHolder
Dim objLoginView As LoginView
Dim objUserName As TextBox
objContentPlaceHolder = CType(Me.FindControl("ContentPlaceHolderBody"), ContentPlaceHolder)
If Not objContentPlaceHolder Is Nothing Then
objLoginView = CType(objContentPlaceHolder.FindControl("loginViewMain"), LoginView)
If Not objLoginView Is Nothing Then
objUserName = objLoginView.FindControl("UserName")
objUserName.Focus()
End If
End If
End Sub
Execution does get into this If structure:
If Not objLoginView Is Nothing Then
Can you tell me what else I need to add in the If structure of this coding to get hold of the User Name TextBox?
You can do that without the need to know the details of the LoginView control. Instead use JavaScript to find the first textbox and focus on it.
Add the following code in your code behind file:
var script = string.Format(#"
var inputs = document.getElementById('{0}').getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {{
var inp = inputs[i];
if (inp.type.toUpperCase() !== 'TEXT') continue;
inp.focus();
inp.select();
break;
}}", this.LoginView.ClientID);
// register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "login focus", script, true);
or in VB.NET:
Dim script = String.Format(
"var inputs = document.getElementById('{0}').getElementsByTagName('input');" &
"for (var i = 0; i < inputs.length; i++) {{" &
" var inp = inputs[i];" &
" if (inp.type.toUpperCase() !== 'TEXT') continue;" &
" inp.focus();" &
" inp.select();" &
" break;" &
"}}", Me.LoginView.ClientID)
' register the script
ScriptManager.RegisterStartupScript(Me, TypeOf(this), "login focus", script, True)
FindControl only searches one tree level deep.
Try using a recursive function instead
for example:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Then the call will be
objLoginView = CType(FindControlRecursive(objContentPlaceHolder, "loginViewMain"), LoginView);
Hope that helps.
I'm using AsyncFileUpload for uploading files, before saving file on server, i rename the selected file. How can I get this new file name in the client side?
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
OnUploadedComplete ="UploadFile1"
OnClientUploadComplete="uploadComplete" ThrobberID="myThrobber" />
Client-side script:
<script>
function uploadComplete(sender, args) {
var fileExtension = args.get_fileName();
}
</script>
Server-side script:
Protected Sub UploadFile1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim fileuploadreceive1 As String = AsyncFileUpload1.PostedFile.FileName
Dim strExtn As String = System.IO.Path.GetExtension(fileuploadreceive1).ToLower
Dim filename1 As String = Path.GetFileName(fileuploadreceive1)
filename1 = "uld" & Math.Round(Rnd() * 2366) & filename1 'changing original file name
Dim fileuploadpath1 As String = Server.MapPath("~") & "\gallery\"
If (strExtn = ".png") Or (strExtn = ".jpg") Or (strExtn = ".gif") Then
AsyncFileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath1, filename1))
End If
End Sub
were you talking about something like:
<%= Page.ResolveClientUrl("~/images/MemoEditor_ABCtoolbar.png") %>
This will get the servers name for it, and then pass what it is called to the client. You can wrap that in some simple javascript or in this example, put it in the src of an image tag.
var x = '<%= Page.ResolveClientUrl("~/images/MemoEditor_ABCtoolbar.png") %>';