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.
Related
I am creating a drag file upload by using Ajax File Upload Control in Asp.net(VB).
I want to show file name, uploaded datetime, file size when I dragged into panel.
How can I do for that setting?
I could change the text for droparea like
$(document).ready(function () {
Sys.Extended.UI.Resources.AjaxFileUpload_Pending = "保留中";
Sys.Extended.UI.Resources.AjaxFileUpload_Remove = "削除";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploaded = "アップロード済";
Sys.Extended.UI.Resources.AjaxFileUpload_Uploading = "アップロード中";
Sys.Extended.UI.Resources.AjaxFileUpload_UploadedPercentage = "アップロード中 {0} %";
Sys.Extended.UI.Resources.AjaxFileUpload_Upload = "アップロード";
document.getElementsByClassName
$(".ajax__fileupload_dropzone").text("ここにファイルをドロップ");
document.getElementsByClassName
$(".ajax__fileupload_uploadbutton").text("アップロード");
});
But I don't know how to change file info display.
This is my drag form and I want to change from application/pdf to uploaded datetime
You can't really display the "time" of up-load until the user starts.
You ALREADY can see the file size in your screen cap, so why the need for that?
you have:
so in above, you see the file name, you see the file size.
However, until such time you hit up-load and start up-loading files, you don't know yet the up-load time as of yet, do you?
So, when you hit up-load files, then each file selected will be up-loaded, and in the server side (code behind), you have this:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
Dim strFileSave As String
strFileSave = Server.MapPath("~/Content/" & e.FileName)
AjaxFileUpload1.SaveAs(strFileSave)
' now code to add say to a database table of files up-loaded.
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL = "INSERT INTO MyUpoadFiles (FileName, UpLoadTime, Size, User_id) " &
"VALUES (#File, #Time,#Size, #User)"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
With cmdSQL.Parameters
.Add("#File", SqlDbType.NVarChar).Value = e.FileName
.Add("#Time", SqlDbType.DateTime).Value = Date.Now
.Add("#Size", SqlDbType.Int).Value = e.FileSize
.Add("#User", SqlDbType.Int).Value = Membership.GetUser.ProviderUserKey
End With
cmdSQL.ExecuteNonQuery()
End Using
End Using
End Sub
Now, when ALL files are up-loaded, then the server side even UpLoadComplete all will fire, and THEN you can take the above list/table and display the files up-loaded along with the FileName, size, and time.
But, you really don't have the ability to display the file information such as what time until such time you uploaded the file and then have the time, right?
Edit:
Perhaps the idea above was not all that clear. What I am suggesting is that you have the up-loader on the page.
So, say we drop in this markup:
<div style="width:40%;padding:25px">
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384" />
<asp:Button ID="cmdDone" runat="server" Text="Done" CssClass="btn" ClientIDMode="Static"/>
<script>
function MyCompleteAll() {
$('#cmdDone').click()
}
</script>
<asp:GridView ID="Gfiles" runat="server" CssClass="table"></asp:GridView>
</div>
And note how we use the client side all done click.
So, we now have this:
We hit upload, and now we see this:
Now we should (need to) hide the Done button - we have the upload clicking on that done button for us.
So that button in theory should become this to hide it:
<asp:Button ID="cmdDone" runat="server" Text="Done"
style="display:none" ClientIDMode="Static"/>
And the code for that button is this:
Protected Sub cmdDone_Click(sender As Object, e As EventArgs) Handles cmdDone.Click
Dim rstFiles As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "select FileName, UpLoadTime, Size, User_id from MyUpLoadFiles"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstFiles.Load(cmdSQL.ExecuteReader)
End Using
End Using
Gfiles.DataSource = rstFiles
Gfiles.DataBind()
' hide up-loader
AjaxFileUpload1.Visible = False
End Sub
I have the following code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Reports</title>
<script language="javascript" src="js/DynamicReports.js" type="text/javascript"></script>
</head>
<body onload="doSelect()">
<asp:DropDownList ID="ddlDynReports" runat="server" DataSourceID="sdsDynReports" DataTextField="DynReportName" DataValueField="DynReportID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDynReports" runat="server" SelectCommand="select v.object_id as DynReportID, substring(v.name, 11, LEN(v.name)) as DynReportName from sys.views v where v.name like 'DynReport[_]%'">
</asp:SqlDataSource>
</body>
</html>
It throws the following error at runtime:
The ConnectionString property has not been initialized.
My web.config file seems to be okay because I am doing many other sql calls in the .vb code. This is the first time I am doing sql in .aspx code.
I presume my connection that is available in my .vb code needs to be exposed to the .aspx code.
I am open to a solution that would move the select to the .vb code.
EDIT: I figured out that I should add ConnectionString="<%$ ConnectionStrings:constr %>" to the SqlDataSource element, but the problem is that I do not have connection strings in my web.config file. My connection strings are in a file called ApplicationConfig.vb.
So, how can I get the connection string out of ApplicationConfig.vb into the .aspx code?
EDIT: I am doing it this way because it is the sample code I found for populating a dropdown from a select statement. I am a vb.net noob so I am basically surviving by cutting and pasting from the SO. Suggestions for better ways is cheerfully accepted but I get lost if the example code is not complete. Example: Some example code I find on SO looks like what I want to do, but it is a series of snip-its and I don't know where to put those snip-its.
EDIT: Add .vb code:
Partial Class XXX_CommonPages_DynamicReports
Inherits System.Web.UI.Page
Protected Sub dynreport_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dynreports_run.ServerClick
Dim ViewObjectId As String = ddlDynReports.SelectedValue
Dim DataOut As String = "some,data,out"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=DynReport_" + ViewObjectId + ".csv")
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Length", DataOut.Length())
Response.Write(DataOut)
' Response.End ' Causes ThreadAbortException.
End Sub
End Class
EDIT: Here is the .vb code that contains the connection string:
Public Class ApplicationConfig
Public Class AppConfig
Implements IConfigurationSectionHandler
Private Const PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT As String = "serve ..."
Public Shared ReadOnly Property ConnectionString() As String
Get
If fieldConnectionString Is Nothing Then fieldConnectionString = PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT
Return fieldConnectionString
End Get
End Property
End Class
End Class
I've seen several questions relating to downloading a PDF from a Web browser using Response, but none seem to fit the mysterious issue I'm having.
I am working on a project that requires the user to be able to click a button (btnPDF) to instantly download a PDF of a Telerik report with a specific "ID" string to the Downloads folder. This process was originally located in an ASPX Page on an IIS separate from where the button is located. When btnPDF was clicked, I used Response.Redirect to download the PDF through that page. The code to download the PDF looked like this:
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
Note that result.DocumentBytes is a byte array containing correct bytes for the PDF.
This code worked fine. Now, instead of having the process on a separate Page in a separate project, I need to merge the process onto the same page where btnPDFis located, so that when you click btnPDF, a subroutine is called that performs the same task. I thought this would be very easy, pretty much a copy and paste. With the same code added in a new subroutine, this is what my click event handler "ButtonPDF_Click" now looks like:
Protected Sub ButtonPDF_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPDF.Click
DownloadReportPDF(Me.RadGrid1.SelectedValue.ToString())
Dim strMessage As String = "alert('Printed PDF Sheet.');"
ScriptManager.RegisterStartupScript(Me, Me.GetType, "MyScript", strMessage, True)
End Sub
Protected Sub DownloadReportPDF(ByVal releaseMasterId As String)
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and download
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
Response.Clear()
Response.ContentType = result.MimeType 'this is always "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Expires = -1
Response.Buffer = True
Response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
Response.BinaryWrite(result.DocumentBytes)
Response.End()
End Sub
But the PDF no longer downloads. An accurate byte array is still created, but the Response portion does not result in the PDF being downloaded from the browser. I've found that putting a call to DownloadReportPDF in the Page_Load handler on the same Page successfully generates and downloads a PDF as it did before.
I can't see any reason why this isn't working, but I'm new to ASP, and I'm not great in VB. I've tried using Response.OutputStream, Response.WriteFile, and making use of a MemoryStream, among several other things that I've lost track of. I'm hoping there's something simple, maybe some sort of property of the Page or btnPDF I could be missing. Here is the markup for btnPDF, just in case:
<asp:linkButton ID="btnPDF" CssClass="btn btn-default" runat="server" Width="115px">
<i class="fa fa-file-text" title="Edit"></i> PDF
</asp:linkButton>
What could be causing such a problem? Where should I look at this point?
Let me know if more information is needed.
Thanks,
Shane
EDIT:
I experimented with setting a session variable on btnPDF_Click, and handling the PDF download on postback. Again, a valid byte array was generated, but the HttpResponse did not cause the PDF to download from the browser.
EDIT:
Building on the last edit, this tells me that calling DownloadReportPDF from Page_Load works only when IsPostBack is false. I just tested this thought, and it holds true. In the above code, if I check IsPostBack at the moment I'm trying to download the PDF, it is true. Investigating further.
Alright, I finally found a solution I'm satisfied with (though I still don't understand why I can't download the PDF using Response while IsPostBack is true).
Inspired by this thread, I put the previously posted code in an HttpHandler called PDFDownloadHandler, then used Response.Redirect in the btnPDF_Click event handler to utilize PDFDownloadHandler. This article helped me a lot on that process, as it is something I have not done before.
In case anyone else runs into this problem, here is the new PDFDownloadHandler:
Imports Microsoft.VisualBasic
Imports System.Web
Imports Telerik.Reporting
Imports Telerik.Reporting.Processing
Public Class PDFDownloadHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As _
System.Web.HttpContext) Implements _
System.Web.IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
Dim path As String = request.Path
If path.Contains("pps.pdfdownload") Then
Dim releaseMasterId As String = request.QueryString("ID")
If releaseMasterId IsNot Nothing Then
'Service call to generate report source
Dim service As New TelerikReportLibrary.ReportServices.PPSReportService
Dim source As Telerik.Reporting.TypeReportSource = service.GetReportSource(releaseMasterId)
'Render PDF and save
Dim reportProcessor As New ReportProcessor()
Dim result As RenderingResult = reportProcessor.RenderReport("PDF", source, Nothing)
Dim fileName As String = result.DocumentName + "_" + releaseMasterId + "." + result.Extension
response.Clear()
response.ContentType = result.MimeType
response.Cache.SetCacheability(HttpCacheability.Private)
response.Expires = -1
response.Buffer = True
response.AddHeader("Content-Disposition", String.Format("{0};FileName={1}", "attachment", fileName))
response.BinaryWrite(result.DocumentBytes)
End If
End If
response.End()
End Sub
Public ReadOnly Property IsReusable() As Boolean _
Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Any further insight on why the original technique did not work is greatly appreciated.
I am trying to get the fileupload control from the ajax control toolkit to work.
I need to use the uploaded files in my code behind (I use asp.net),
This includes unzipping, resizing and putting some data in a database.
The problem I have is that when I use ajaxUpload1_OnUploadComplete, i can't get the text from a textbox on the same page.
When I use a breakpoint, I noticed that the value of the textbox is just "".
I have searched a lot and I really can't find a solution for this, so I hoped that someone here might be able to help.
I have pasted my code below, thanks in advance!
.aspx code:
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"
CodeFile="Upload.aspx.vb" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="LblUploadError" runat="server" Text="Please login first" Visible="false"></asp:Label>
<asp:Panel ID="PnlUpload" runat="server" Visible="false">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<span>Album name:</span><br />
<asp:TextBox ID="txtAlbumNaam" runat="server" ViewStateMode="Disabled"></asp:TextBox><br />
<span>Private album</span> <asp:CheckBox ID="chkPrivate" runat="server" /><br />
<span>Upload files (.zip, .jpg, .jpeg or .png)</span><br />
<asp:AjaxFileUpload id="ajaxUpload1" OnUploadComplete="ajaxUpload1_OnUploadComplete" ThrobberID="MyThrobber" runat="server" AllowedFileTypes="jpg,jpeg,zip,png" /><br />
<asp:Label ID="lblError" runat="server"/><br />
</asp:Panel>
</asp:Content>
code behind:
Imports Ionic.Zip
Imports System.IO
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("LoggedIn") = True Then
PnlUpload.Visible = True
Else
LblUploadError.Visible = True
End If
End Sub
Protected Sub ajaxUpload1_OnUploadComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AjaxFileUploadEventArgs)
'indien zip:
Dim ziperror As Boolean = False
If System.IO.Path.GetExtension(e.FileName) = ".zip" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempZips/" & e.FileName.ToString))
Dim ZipToUnpack As String = Server.MapPath("./TempZips/" & e.FileName.ToString)
Dim UnpackDirectory As String = Server.MapPath("./TempFotos")
Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
Dim file As ZipEntry
For Each file In zip1
Dim strExtensie As String = System.IO.Path.GetExtension(file.ToString)
If Not (strExtensie = ".jpeg" Or strExtensie = ".jpg" Or strExtensie = ".png") Then
ziperror = True
lblError.Text = "The .zip structure is incorrect, please make sure that you only have compatible pictures inside the zip file."
End If
Next
If ziperror = False Then
For Each file In zip1
file.Extract(UnpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Next
End If
End Using
'indien foto:
ElseIf System.IO.Path.GetExtension(e.FileName) = ".jpeg" Or System.IO.Path.GetExtension(e.FileName) = ".jpg" Or System.IO.Path.GetExtension(e.FileName) = ".png" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempFotos/" & e.FileName.ToString))
Else
'indien geen van beide
lblError.Text = "Invalid filetype on one of the files, please use other files."
End If
'tempzips leegmaken
If ziperror = False Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Server.MapPath("TempZips"))
File.Delete(foundFile)
Next
'verkleinen en album toevoegen aan database:
Dim strFolderDirectory As String = Server.MapPath("users/" & Session("UserNickName") & "/" & txtAlbumNaam.Text)
System.IO.Directory.CreateDirectory(strFolderDirectory)
Dim strDirectory As String = Server.MapPath("TempFotos")
Dim intAantalFotos As Integer = 0
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
Using Afbeelding As System.Drawing.Image = System.Drawing.Image.FromFile(foundFile)
Dim resizedimage As System.Drawing.Image
Dim resizedwidth As Integer
resizedwidth = (300 / Afbeelding.Height) * Afbeelding.Width
resizedimage = Afbeelding.GetThumbnailImage(resizedwidth, 300, Nothing, New IntPtr)
resizedimage.Save(strFolderDirectory & "/" & Path.GetFileName(foundFile))
End Using
intAantalFotos += 1
Next
Dim CmdInsert As New OleDbCommand
Dim Sqlstatement As String = "INSERT INTO tblAlbums (userID, createdDate, pictures, private, albumName) VALUES (#userID, Now(), #pictures, #private, #albumName);"
CmdInsert.Connection = dbConn.cn
CmdInsert.CommandText = Sqlstatement
CmdInsert.Parameters.AddWithValue("userID", CInt(Session("userID")))
CmdInsert.Parameters.AddWithValue("pictures", intAantalFotos)
CmdInsert.Parameters.AddWithValue("private", chkPrivate.Checked)
CmdInsert.Parameters.AddWithValue("albumName", txtAlbumNaam.Text)
dbConn.cn.Close()
dbConn.cn.Open()
CmdInsert.ExecuteNonQuery()
dbConn.cn.Close()
'TempFotos leegmaken
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
File.Delete(foundFile)
Next
'pagina herladen
LblUploadError.Visible = True
LblUploadError.Text = "Your pictures have been successfully uploaded!"
End If
End Sub
End Class
The problem is that ajax control toolkit file upload control can upload files to server using hidden iFrame (depending on what HTML5 features browser supports). Hidden iFrame references to the same url as you page and that's why you page loaded once more but only to hidden iframe. That's why on server side during handling UploadComplete event you get that the text box has empty value (because it is really have empty value because this is the state of the page which was loaded in iframe).
One of the solution to your problem is performing additional logic (which depends on entered data) after uploading is complete. To do this you can handle client side upload complete event and perform postback (or ajax request) manually.
Other solution can be setting content of the hidden iFrame elements manually before upload will start. In this case you can get hidden iframe, found necessary HTML elements (like text input in your case) and set it value the same as it was entered by user. But this approach can required extending logic of the ajax control toolkit upload control on client side.
Morning All,
I would like to have a cancel button on my web page that essentially i would like to clear form field and themn redirect users to the home page.
I have 7 txt boxes that i will need to clear before the page redirects. I have done some searching on the internets and have tried to put the following sample into my page with no luck....
With this code i get an error on the X = "" line. I get a message 'Value of type string cannt be converted to system.we.UI.control'
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
x = " "
End If
Next
End Sub
And i have also tried the below which also produces a Compilation Error.
For Each c As Control In Me.Controls
If TypeOf c Is TextBox Then
DirectCast(c, TextBox).Text = ""
End If
Next
Can anyone help me with resolving this issue?
Regards
Betty
Try this:
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
Dim txt as TextBox = x
txt.Text = ""
End If
Next
Explanation:
You tried to set a string to a Control-variable and of course the compiler does not know how to to this.
The version I gave will set the Text-property of each TextBox to the empty-String
You can use html code to reset all field of current form you are working with
use follwoing code to reset all fields
<input type="reset" value="Clear" onclick="redirectFunction()" />
and in redirectFunction write following javascript code:
function redirectFunction()
{
window.location="destination.aspx";
}
using above code you can redirect to destination page.