locked
How To: Upload Images / Files to a http IIS server?

    Question

  • Hi Everyone,

    I am very new to .NET web coding and recently I have been struggling to search information about uploading files (mostly images) to a web server (runs under IIS 5 and above - currently testing under IIS 5)

    I have searched through examples and I came across a sample code that looks something like this (I have modified the sample codes)       

    If My.Computer.Network.IsAvailable = True Then
      'FU1 is asp:Fileupload object
      Dim _username as String = "username"
      Dim _password as String = "password"
      Dim _sourceFile as String = "C:\146200882.tif"
      Dim _desFile as String = "http://remoteserver/FileShare/uploaded.tif"
      If FU1.FileName.Length > 0 Then 
        Try
         Dim _client As New WebClient
         _client.Credentials = New System.Net.NetworkCredential(_username, _password)
    
         _client.UploadFile(_desFile, "PUT", _sourceFile)
        Catch ex As Exception
           Page.Response.Write(ex.Message)
        End Try
      End If
    
    End If
    

    This seems to work, unfortunately, when I try to type "http://remoteserver/FileShare/uploaded.tif" on the browser address bar, instead of previewing the TIF image, it automatically prompts "Save as" window.

    This happens the same with txt files, or whatever files I tried to upload.

    What is wrong with the code I used? Is it because it is saved as Byte format that the browsers no longer identify and preview the files?

    Is there other method that I can use to upload files? I have tried searching through pages of msdn but most of the examples are in C# and a lot of them doesn't really work when I try to convert them into VB.net (plenty of errors, even though I followed msdn examples).

    Please help. This is really frustrating a beginner like me. I do not know where else to find good examples in VB.Net.

    Regards

    Jessicca

     

    Monday, November 15, 2010 11:36 AM

Answers

  • Jessica,

    Here's some code that will handle any file size:

    Public Shared Sub FTPUpload(filename As [String], Server As [String], Login As [String], Password As [String])
    	Dim fileInf As New FileInfo(filename)
    	Dim uri As String = ("ftp://" & Convert.ToString(Server) & "/") + fileInf.Name
    	Dim reqFTP As FtpWebRequest
    
    	reqFTP = DirectCast(FtpWebRequest.Create(New Uri(("ftp://" & Convert.ToString(Server) & "/") + fileInf.Name)), FtpWebRequest)
    	reqFTP.Credentials = New NetworkCredential(Login, Password)
    	reqFTP.KeepAlive = False
    	reqFTP.Method = WebRequestMethods.Ftp.UploadFile
    	reqFTP.UseBinary = True
    	reqFTP.ContentLength = fileInf.Length
    
    	Dim buffLength As Integer = 2048
    	Dim buff As Byte() = New Byte(buffLength - 1) {}
    	Dim contentLen As Integer
    
    	Dim fs As FileStream = fileInf.OpenRead()
    
    	Try
    		Dim strm As Stream = reqFTP.GetRequestStream()
    		contentLen = fs.Read(buff, 0, buffLength)
    		While contentLen <> 0
    			strm.Write(buff, 0, contentLen)
    			contentLen = fs.Read(buff, 0, buffLength)
    		End While
    
    		strm.Close()
    		fs.Close()
    	Catch ex As Exception
    		Throw New Exception(ex.Message)
    	End Try
    End Sub
    
    Adam
    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Thursday, November 25, 2010 4:05 AM
  • You can use a filesystemwatcher to act on the folder: http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

    Adam


    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Saturday, November 27, 2010 2:49 PM
  • Web services don't typically act on the local drive. They are referenced through a project to exchange information between applications.

    A "Windows" service with the fliesystemwatcher would be a better choice. You "can" use a stand alone application to accomplish the same result but services run without a user being logged in. An application would require someone being logged at all times.

    -Adam


    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Tuesday, November 30, 2010 7:54 AM

All replies

  • Hi, there is not a problem related with your code, is related with the WebBroser,

     

    If you see this: http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support, you can see that the biggest Browser that support Tif files is Safari(MAC).

    Instead of uploadin a TIF file, try with a jpg.


    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno
    Monday, November 15, 2010 11:45 AM
  • Hi Jtorrecilla ,

    Thank you so much for the prompt reply.

    Unfortunately this happens to JPG, TXT, practically any file I tried uploading.

    My browser is Firefox 3.6, which is the latest browser.

    So besides the browser issue, what else should I look into / set, especially if I need to upload large PDF files which is more than 500 bytes (in future)? I heard that this example will have issues with larger file sizes.

    Please help

    Monday, November 15, 2010 11:53 AM
  • Currently, I can't check this problem.

    Have you got permissions to admin the IIS? 

    I think that it may be an IIS config problem. but not sure.


    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno
    Monday, November 15, 2010 11:55 AM
  • Hi Jtorrecilla ,

    I am not sure whether it is IIS configuration problem, but I have admin access to the test IIS.

    Is there other coding methods I can upload files, especially more than 500 bytes?

    Tuesday, November 16, 2010 12:30 AM
  • In my idea is that a security option (from which I'm very happy).

    I would not like it if you could upload all kind of files from my  computer simply because I got a piece of trial software from you.


    Success
    Cor
    Tuesday, November 16, 2010 9:26 AM
  • In my idea is that a security option (from which I'm very happy).

    I would not like it if you could upload all kind of files from my  computer simply because I got a piece of trial software from you.


    Success
    Cor


    Err... I do not quite understand what you are trying to tell me. Could you elaborate a bit more?

    True enough we cannot copy all kinds of files, which you just gave me an idea, where restricted files are to be uploaded, like pdf, jpg, tiff, png, txt. But the codes I used from my first post will turn all files to "auto download" once it is uploaded, instead of enabling them to be viewed on the browser.

    Therefore my challenge is to find any useful example codes in VB.NET (I've never code in C# before) that can help me with this.

    Monday, November 22, 2010 10:15 AM
  • Jessicca, have you evalueate instead of ussing a WebClient using a FTP Client,

    It is probably sure that with an FTP client you have no restrictions to upload any kind of file, 

    But the Tiff, problems persists with the visualization.


    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno
    Monday, November 22, 2010 11:37 AM
  • Jessicca, have you evalueate instead of ussing a WebClient using a FTP Client,

    It is probably sure that with an FTP client you have no restrictions to upload any kind of file, 

    But the Tiff, problems persists with the visualization.


    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno


    Jtorrecilla ,

    I am not familiar with FTP transfer, but it WILL be a problem if there's a TIFF visualization issue at hand, as most of the files uploaded will most likely be in TIFF format.

    :(

    Tuesday, November 23, 2010 1:52 AM
  • I explain you previously that show a TIFF in the browser must be a problem due to the limits of the Browser only 2 allow Tiff files...
    Javier Torrecilla
    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno
    Tuesday, November 23, 2010 7:13 AM
  • I explain you previously that show a TIFF in the browser must be a problem due to the limits of the Browser only 2 allow Tiff files...
    Javier Torrecilla
    Para el correcto funcionamiento, y que otros usuarios se puedan beneficiar de la solucion de esta pregunta por favor marca las respuestas que te hayan ayudado como "Respuesta".
    Si la respuesta te ha sido util Votala.
    Mi Blog: Jtorrecilla
    Enlace a Faq de Winforms en Ingles Muy bueno

    As for TIFF files, I have a free plug in that allows a proper viewing of a TIFF file on the browser (including zoom in and out). My problem right now is that I need to find a way copy the files and not allowing the "auto download" window to pop up once it is uploaded.

    Let me give you a scenario that I might want to use.

    After talking to my boss, and thinking of using webservice to run the back-end file copy, I need to fulfill this scenario:

    1. User A (remote) -> navigates to an aspx page with FileUpload objects.

    2. IIS will run such code and copy it to a temporary folder in the webserver:

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        'All testing data -----------------------------------------------------------
    
        Dim _testWebFolder As String = System.AppDomain.CurrentDomain.BaseDirectory
        If Not Right$(_testWebFolder, 1) = "\" Then _testWebFolder += "\"
        _testWebFolder += "temp\"
    '----------------------------------------------------------------------------
        If My.Computer.Network.IsAvailable = True Then
          Dim oFile As FileUpload = New FileUpload
          oFile = FU1
          If oFile.PostedFile.ContentLength > 0 Then
            Dim sTempFilename As String = System.IO.Path.GetFileName(FU1.PostedFile.FileName)
            oFile.SaveAs(_testWebFolder & sTempFilename)
          End If
    
          oFile = Nothing
        End If
    End Sub
    

    3. IIS calls webservice, that will copy the file from the temporary webfolder to the designated shared folder that is another machine that stores the data and is linked via IIS (virtual directory).

    4. User can see uploaded file via the virtual directory.

    Tuesday, November 23, 2010 9:59 AM
  • Jessica,

    That's what is supposed to happen. By using the URL to the file, you're telling the browser to open the file as if you double-clicked it on your desktop.

    If you want to preview the image, you'll need to create a page that has an image control. Create some hyperlinks that point to the fixed location of the images on your server and load them into the image control.

    Adam


    Ctrl+Z
    Thursday, November 25, 2010 4:00 AM
  • Jessica,

    Here's some code that will handle any file size:

    Public Shared Sub FTPUpload(filename As [String], Server As [String], Login As [String], Password As [String])
    	Dim fileInf As New FileInfo(filename)
    	Dim uri As String = ("ftp://" & Convert.ToString(Server) & "/") + fileInf.Name
    	Dim reqFTP As FtpWebRequest
    
    	reqFTP = DirectCast(FtpWebRequest.Create(New Uri(("ftp://" & Convert.ToString(Server) & "/") + fileInf.Name)), FtpWebRequest)
    	reqFTP.Credentials = New NetworkCredential(Login, Password)
    	reqFTP.KeepAlive = False
    	reqFTP.Method = WebRequestMethods.Ftp.UploadFile
    	reqFTP.UseBinary = True
    	reqFTP.ContentLength = fileInf.Length
    
    	Dim buffLength As Integer = 2048
    	Dim buff As Byte() = New Byte(buffLength - 1) {}
    	Dim contentLen As Integer
    
    	Dim fs As FileStream = fileInf.OpenRead()
    
    	Try
    		Dim strm As Stream = reqFTP.GetRequestStream()
    		contentLen = fs.Read(buff, 0, buffLength)
    		While contentLen <> 0
    			strm.Write(buff, 0, contentLen)
    			contentLen = fs.Read(buff, 0, buffLength)
    		End While
    
    		strm.Close()
    		fs.Close()
    	Catch ex As Exception
    		Throw New Exception(ex.Message)
    	End Try
    End Sub
    
    Adam
    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Thursday, November 25, 2010 4:05 AM
  • Thank you Adam, for the suggested codes. I will try them out ASAP!

    Right now I have another hurdle, which is after the remote user uploads the file to the IIS temporary folder, a web service (or something equivalent) needs to pull the files to the right folder, which resides on another machine in the network and shared out as a virtual directory from IIS.

    Any suggestion of codes / advise you would like to give me? (Suggestion would be better as I am still very unfamiliar in .NET coding)

    Friday, November 26, 2010 8:32 AM
  • You can use a filesystemwatcher to act on the folder: http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

    Adam


    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Saturday, November 27, 2010 2:49 PM
  • Adam, do you mean I use the examples of the code on a web service, or do I create a running application with intervals to check through the folder?
    Monday, November 29, 2010 2:51 AM
  • Web services don't typically act on the local drive. They are referenced through a project to exchange information between applications.

    A "Windows" service with the fliesystemwatcher would be a better choice. You "can" use a stand alone application to accomplish the same result but services run without a user being logged in. An application would require someone being logged at all times.

    -Adam


    Ctrl+Z
    • Marked as answer by Liliane Teng Tuesday, December 07, 2010 5:03 AM
    Tuesday, November 30, 2010 7:54 AM