How to get serverside filename in clientside while using AsyncFileUpload - asp.net

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") %>';

Related

How to print a server side text file on a client printer programically

I have a server side application which creates a series of text files on the server. I need to allow a user to print one or more of the files directly on the client printer by clicking a button on a web page. That should bring up a printer selection window and then commence printing the selected web pages. I can handle the file selection and the printer selection windows but have not been able to get the files to print. I located code on Code Project (http://www.codeproject.com/Tips/689325/Send-PDF-files-directly-to-client-printer-without) which was described as doing exactly what I need but for for PDF files. I have attempted to adapt it to text files and the code runs without visible error, but nothing arrives at the printer and I do not know how to locate what happens after the code executes the value attribute of the Object tag of the web pages source code (see below). I program in VB.Net.
Here is the object tag in the source code:
<object id = "Object1" name="Txt1"
type="file/txt" width="1" height="1" >
<param name='SRC' value='<%= SReportFileName %>'/>
</object>
Here is the code from the code behind file:
Partial Class ViewResults_PrintingReports
Inherits System.Web.UI.Page
Public SReportFileName As String = ""
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PathName As String = ""
Dim Uname As String = ""
Dim Iyr As String = ""
Dim Iwld As String = ""
Dim Iqtr As String = ""
Dim FName As String = ""
Dim CNumber As String = ""
Uname = "UserName"
Iyr = "3"
Iqtr = "1"
FName = "ReportA"
CNumber = "1"
Iwld = "1"
' Dim cs As ClientScriptManager = Page.ClientScript
PathName = "~/Competitions/" & Uname & "/BP/" & "World" & Iwld & "/Reports/QtrRpts" & Iwld & "." & Iyr & Iqtr & "/" & FName & "." & Iwld & CNumber & ".txt"
SReportFileName = PathName '// temp/mypdf.pdf
Try
ClientScript.RegisterStartupScript(GetType(Page), "MessagePopUp", "<script language=text/javascript>document.Txt1.printAll()</script>")
Catch ex As Exception
MsgBox("Problem printing file", , ex.Message)
End Try
End Sub
End Class
Any help would be appreciated.
You need to call javascript.
Here is the javascript
function PrintFile(FilePath) {
var printWin = window.open(FilePath, '','left=0,top=0,width=700,height=700,status=0');
printWin.focus();
printWin.print();
}
This is the codebehind of the button
Dim FilePath As String
FilePath = "This is your File Path"
Dim PrintFile As String
PrintFile = "PrintFile('" & FilePath & "')"
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ntmtch", PrintFile, True)

New Google Recaptcha with ASP.Net

I am attempting to get the new Google reCaptcha working in my ASP.NET project and I am having problems getting it to be the new one "I'm not a robot".
I had the old one in there and after doing much research on the developers.google.com web site, everything looks the same (they even point me to a download of the same dll - 1.0.5). So, I got the new keys and put them in and it works but it looks just like the old reCaptcha.
Has anyone gotten the new one to work with their ASP.Net? What am I missing?
EDIT:
So playing around in a test app and searching some other web sites I found that if I create a page like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form id="form1" runat="server" action="?" method="POST">
<div>
<div class="g-recaptcha" data-sitekey="My Public Key"></div>
<br/>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
And then in my code-behind (Button1_Click), I do this:
Dim Success As Boolean
Dim recaptchaResponse As String = request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Success = True
Else
Success = False
End If
The recaptchaResponse will either be empty or filled in depending on if they are a bot or not. The issue is, I now need to take this response and send it to google with my private key so I can verify that the response was not provided by a bot, in my code-behind, but I cannot figure out how. I tried this (in place of Success = True):
Dim client As New System.Net.Http.HttpClient()
client.BaseAddress = New Uri("https://www.google.com/recaptcha/")
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim response As Net.Http.HttpResponseMessage = Await client.GetAsync("api/siteverify?secret=My Private key&response=" + recaptchaResponse)
If (response.IsSuccessStatusCode) Then
Dim CaptchResponse As ReCaptchaModel = Await response.Content.ReadAsAsync(Of ReCaptchaModel)()
Success = CaptchResponse.success
Else
Success = False
End If
But, I could not figure out how to get the async stuff working and I cannot find anything on what ReCaptchaModel is, so I found another way to call a web service and get a json response and tried this instead:
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/")
Dim Data As String = "api/siteverify?secret=My Private Key&response=" + recaptchaResponse
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = "{""data"":""" + Data + """}"
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
'get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
Stop
End Using
End Using
But, this just gives me the content of the web page at https://www.google.com/recaptcha. Not what I want. The Google page isn't very useful and I am stuck on where to go. I need some help either calling the Google verify service or if anyone has found another way to do this from ASP.NET.
I had just about given up when I ran across something unrelated that made me think about it again and in a different way. In my last attempt above, I was attempting to pass the private key and recaptcha response as the data, so I tried it in the create of the WebRequest and it worked. Here is the final solution:
Using the same HTML posted above, I created a function that I can call in the button click event where I check the Page.IsValid and call this function:
Private Function IsGoogleCaptchaValid() As Boolean
Try
Dim recaptchaResponse As String = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(recaptchaResponse) Then
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=My Private Key&response=" + recaptchaResponse)
request.Method = "POST"
request.ContentType = "application/json; charset=utf-8"
Dim postData As String = ""
'get a reference to the request-stream, and write the postData to it
Using s As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(s)
sw.Write(postData)
End Using
End Using
''get response-stream, and use a streamReader to read the content
Using s As IO.Stream = request.GetResponse().GetResponseStream()
Using sr As New IO.StreamReader(s)
'decode jsonData with javascript serializer
Dim jsonData = sr.ReadToEnd()
If jsonData = "{" & vbLf & " ""success"": true" & vbLf & "}" Then
Return True
End If
End Using
End Using
End If
Catch ex As Exception
'Dont show the error
End Try
Return False
End Function
I'm sure there are improvements to be made to the code, but it works. I couldn't see adding references to some JSON libraries for reading one thing I just check the string.
Thank you for sharing this. It worked for me. I went ahead and converted it to C# (since that's what I was using) and added a few things.
I changed the validation step. I split the JSON string and evaluated if success was found where it should be.
I used the ConfigurationManager to store the ReCaptcha Keys.
Finally, I changed it from using a WebRequest to using and HttpClient. This cut the code in half because I don't need to read the stream now.
Feel free to use this code as well.
private static bool IsReCaptchaValid(string response)
{
if (string.IsNullOrWhiteSpace(response))
{
return false;
}
var client = new HttpClient();
string result =
client.GetStringAsync(string.Format("{0}?secret={1}&response={2}", ConfigurationManager.AppSettings["ReCaptchaValidationLink"],
ConfigurationManager.AppSettings["ReCaptchaSecretKey"], response)).Result;
string[] split = result.Split('\"');
return split[1] == "success";
}
I took a slightly different approach, using the data-callback option and a Session parameter. The following sits within the MainContent block of the .aspx file:
<asp:ScriptManager ID="scrEnablePage" EnablePageMethods="true" runat="server" />
<asp:Panel ID="pnlCaptcha" runat="server" Visible="true">
<div class="g-recaptcha"
data-sitekey='<asp:Literal ID="litKey" runat="server" Text="<%$ AppSettings:recaptchaPublicKey%>" />'
data-callback="handleCaptcha"></div>
</asp:Panel>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
function handleCaptcha(e) {
PageMethods.RecaptchaValid(e);
location.reload(true);
}
</script>
Then in the code-behind:
Private Const GoogleUrl As String = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
pnlCaptcha.Visible = Not (Session("VerifiedHuman") = "True")
...
End Sub
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Sub RecaptchaValid(response As String)
Dim client As New System.Net.WebClient()
Dim outcome As Dictionary(Of String, String)
Dim result As String = String.Join(vbCrLf,
{"{", """success"": true", "}"})
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim url As String = String.Format(GoogleUrl,
ConfigurationManager.AppSettings.Get("recaptchaPrivateKey"),
response)
Try
result = client.DownloadString(url)
Catch ex As System.Net.WebException
Exit Sub ' Comment out to default to passing
End Try
outcome = serializer.Deserialize(Of Dictionary(Of String, String))(result)
HttpContext.Current.Session("VerifiedHuman") = outcome("success")
End Sub
Now in Page_Load you can check Session("VerifiedHuman") = "True" and update your page controls accordingly, hiding the panel with the Captcha control and showing the other appropriate items.
Note that this takes the keys from Web.config, i.e.
<configuration>
<appSettings>
<add key="recaptchaPublicKey" value="..." />
<add key="recaptchaPrivateKey" value="..." />
...
</appSettings>
...
</configuration>
This adds a few things. It converts the response from Google into a Json object, it adds a timeout on the verification request, and it adds a verification of the hostname (required by Google if sending requests from multiple domains and the domains aren't listed in the Google Admin area).
Imports Newtonsoft.Json
Public Class Google
Public Class ReCaptcha
Private Const secret_key = "YOUR_SECRET_KEY"
Public Shared Function Validate(Request As HttpRequest, hostname As String) As Boolean
Dim g_captcha_response = Request.Form("g-recaptcha-response")
If Not String.IsNullOrEmpty(g_captcha_response) Then
Dim response = ExecuteVerification(g_captcha_response)
If Not response.StartsWith("ERROR:") Then
Dim json_obj = JsonConvert.DeserializeObject(Of ValidateResponse)(response)
If json_obj.success Then
If json_obj.hostname.ToLower = hostname.ToLower Then Return True
End If
End If
End If
Return False
End Function
Private Shared Function ExecuteVerification(g_captcha_response As String) As String
Dim request As Net.WebRequest = Net.WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" & secret_key & "&response=" & g_captcha_response)
request.Timeout = 5 * 1000 ' 5 Seconds to avoid getting locked up
request.Method = "POST"
request.ContentType = "application/json"
Try
Dim byteArray As Byte() = Encoding.UTF8.GetBytes("")
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As Net.WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
Return "ERROR: " & ex.Message
End Try
End Function
Public Class ValidateResponse
Public Property success As Boolean
Public Property challenge_ts As DateTime
Public Property hostname As String
<JsonProperty("error-codes")>
Public Property error_codes As List(Of String)
End Class
End Class
End Class
So in the button's Click event, just call:
If Google.ReCaptcha.Validate(Request, Request.Url.Host) Then
' good to go
Else
' validation failed
End If

Uploading multiple files from a File Input control

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!

Server.CreateObject(“Scripting.FileSystemObject”) issue - Object required:Server (code:0) ASP/VBscript

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

vb.net upload file problem

When I try to post a file its coming back false ie there was no file attached. Can anyone see anything wrong with this? Or what might be causing it.
<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="cmdSubmitApplication" runat="server" Text="Button" />
</form>
Protected Sub cmdSubmitApplication_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmitApplication.Click
If Me.fileUpload.PostedFile Is Nothing Then
Response.Write("You must specify file to upload!")
Else
Try
Dim strExt As String = Path.GetExtension(Me.fileUpload.PostedFile.FileName)
If strExt.ToLower() = ".doc" Then
Dim savedFile As String
savedFile = Path.GetFileName(Me.fileUpload.PostedFile.FileName)
Me.fileUpload.PostedFile.SaveAs(Server.MapPath("cvs\") & savedFile)
Response.Write("File Uploaded Successfully")
Else
Response.Write("Only Image Files are Allowed")
End If
Catch exp As Exception
Response.Write(exp.Message)
End Try
End If
End Sub
Try using:
If Me.fileUpload.HasFile Then
Response.Write("You must specify file to upload!")
Else
here is a full working example from MSDN:
http://msdn.microsoft.com/en-us/kb/kb00323245.aspx
please have a look.
also try replacing "If Me.fileUpload.PostedFile Is Nothing Then" with "If fileUpload.PostedFile Is Nothing Then"
and check permissions on the destination folder
Try removing the enctype="multipart/form-data" from the form tag. I'm looking at my pages that I use the upload on and they don't have it.
I have the form tag in a master page, but it's just:
< form id="form1" runat="server" >
< form >
Public Sub UploadFile(ByVal BugID As System.Guid, ByVal Files As System.Web.UI.WebControls.FileUpload, ByVal fileDescription As String)
Dim guid As System.Guid = System.Guid.NewGuid()
Dim filesSave As New BugTrackerData.Files.Files()
Dim filename As String = Files.PostedFile.FileName
'Grab the file name from its fully qualified path at client
Dim strFileName As String = guid.ToString() & System.IO.Path.GetExtension(filename)
'Save uploaded file to server at C:\ServerFolder\
Dim savepath As String = System.Web.HttpContext.Current.Server.MapPath("~/Resources/FileUploads/" & strFileName)
Try
If Not String.IsNullOrEmpty(FileUpload1.FileName) Then
Files.PostedFile.SaveAs(savepath)
filesSave.SaveToDB(guid, BugID, strFileName, fileDescription)
End If
Catch Exp As Exception
Throw Exp
End Try
End Sub
fixed it. There was a tag in the master, so the form I added below was nested. I removed the form tag from the master. Would that cause problems elsewhere. Should I just remove the form tag above instead of the master.
ps I hate vb.net and everything about it.

Resources