Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

File download

Posted on 2014-04-08
18
Medium Priority
?
269 Views
Last Modified: 2014-04-09
Hi,

I don't know what is wrong with my code.
but what I am trying to do is let the user save or open the file when they click on the file name.

the file is saved as an object in the database.



this is what I have so far.

thanks,
Lulu

THIS PART OF CODE WORKS FINE IT SAVES THE FILE IN THE DATABASE.



<!--- Insert Uploaded files --->
 <cfset filelocation = expandpath('uploadedfiles/')> 
<cfset maxFiles = 3>
<cfset Attachments="">
      <cfloop from="1" to="#variables.maxFiles#" index="ii">
      <cftry>
            <cfif StructKeyExists(form,"AttachFile" & ii) && len(trim(Form["AttachFile" & ii]))>
             
             <cfset variables["Descp" & ii] = Form["FileDescription" & ii]>
             <cfset variables["FileName" & ii] = Form["FileName" & ii]>

             <CFFILE ACTION="UPLOAD"
                        FILEFIELD="AttachFile#ii#"
                        DESTINATION="#variables.filelocation#"
                        NAMECONFLICT="makeunique">
     
             <cfset Attachments=ListAppend(variables.Attachments,cffile.serverfile)>  
          
         </cfif>
            <cfcatch>
            <br>#cfcatch.message#<br>#cfcatch.detail#<br>
            #cfcatch.tagContext[1].template# Line #cfcatch.tagContext[1].line#
            </cfcatch></cftry>
      </cfloop>

            <cfif len(trim(variables.Attachments))> 
   
      <cfquery name = "QLogFiles"  datasource="#strDSN#" username="#strUID#" password="#strPWD#">
			Set Nocount On;
				<cfset cnt=0>
                   <cfloop list="#variables.Attachments#" index="ii">
            <cfset cnt++/>	
      <cfif FileExists(variables.filelocation & ii)>

                  INSERT INTO Files
                        (FileName,UploadedFile,IssueID,Status,CreatedDate)
                  VALUES
                        ( 
                        <cfif #variables["Descp" & cnt]# neq ''>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["Descp" & cnt]#">, 
                        <cfelse>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["FileName" & cnt]#">, 
                        </cfif>
                     
                        <cfqueryparam cfsqltype="cf_sql_blob"
                                value="#FileReadBinary(variables.filelocation & ii)#">,
                    #IssueIDVal#, 
                    1, 
                    <cfqueryparam cfsqltype="cf_sql_date" value="#Now()#" />  )          
        </cfif> 
      </cfloop>
</cfquery>
</cfif>

Open in new window





HERE WHERE I WANT IT TO DOWNLOAD THE FILE TO EITHER SAVE IT OR OPEN IT


<cfquery name = "QGetFile"  datasource='#strDSN#' username='#strUID#' password='#strPWD#' result="r">
    select UploadedFile from files
    where Status = 1 and IssueID = <cfqueryparam cfsqltype="cf_sql_numeric" value="#url.ID#">
</cfquery>    
        
 <!---<cfdump var="#QGetFile#" />  --->
 <cfset convertfile = toString(QGetFile.UploadedFile)>
<!---<cfoutput>SQL: #r.SQL#</cfoutput>  --->


<cfsetting enablecfoutputonly="yes">
<CFIF isDefined("QGetFile") and QGetFile.RecordCount gt 0>
  <cfoutput query="QGetFile"> 
    <cfset convertfile = toString(QGetFile.UploadedFile)> 
  	<a href="javascript:void(0);" onclick="openWindow('#convertfile#','#URL.ID#')">#convertfile#</a> 
  </cfoutput>
</CFIF>
<cfif isDefined('url.file') and url.file neq ''>
	<cfcontent type="application/x-unknown">
	<cfheader name="Content-disposition" value="attachment;filename=#url.file#">

    <cfcontent variable="#ExpandPath('uploadedfiles/#ToSring(ToBinary(url.file))#')#" reset="true" type="text/plain, application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> 
    
</cfif>  

Open in new window


this is what I am getting right now on my page.

file
0
Comment
Question by:lulu50
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
18 Comments
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39987869
did you tried my code in your old question, rather than opening a new question.

I pasted the whole code there
0
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39987926
there aremany functions avaliable like

tostring
charsetencode

to convert your binary data to string, so you as not following my suggestions, good luck now

cheers

here is your original code as i tried again:

<!--- Insert Uploaded files --->
<cfsetting showdebugoutput="yes">
<cfset filelocation = expandpath('uploadedfiles/')>
<cfset maxFiles = 3>
<cfset Attachments="">
<cfif isdefined('form.submit')>
<cfloop from="1" to="#variables.maxFiles#" index="ii">
  <cftry>
    <cfif StructKeyExists(form,"AttachFile" & ii) && len(trim(Form["AttachFile" & ii]))>
      <cfset variables["Descp" & ii] = Form["FileDescription" & ii]>
      <cfset variables["FileName" & ii] = Form["AttachFile" & ii]>
      <CFFILE ACTION="UPLOAD"
                        FILEFIELD="AttachFile#ii#"
                        DESTINATION="#variables.filelocation#"
                        NAMECONFLICT="makeunique">
      <cfset Attachments=ListAppend(variables.Attachments,cffile.serverfile)>
    </cfif>
    <cfcatch>
    <cfoutput>
      <br>
      #cfcatch.message#<br>
      #cfcatch.detail#<br>
      #cfcatch.tagContext[1].template# Line #cfcatch.tagContext[1].line#
    </cfoutput>  
    </cfcatch>
  </cftry>
</cfloop>
<cfif len(trim(variables.Attachments))>
  
				<cfset cnt=0>
                   <cfloop list="#variables.Attachments#" index="ii">
            <cfset cnt++/>	
      <cfif FileExists(variables.filelocation & ii)>
      <cfquery name = "QLogFiles">
                  INSERT INTO Files
                        (FileName,UploadedFile,IssueID,Status,CreatedDate,uploadedasbinary)
                  VALUES
                        ( 
                        <cfif #variables["Descp" & cnt]# neq ''>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["Descp" & cnt]#">, 
                        <cfelse>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["FileName" & cnt]#">, 
                        </cfif>
                     
                        <cfqueryparam cfsqltype="cf_sql_longvarchar"
                                value="#ToBase64(variables.filelocation & ii)#">,
                    1,
                    1,
                    <cfqueryparam cfsqltype="cf_sql_date" value="#Now()#" />,
                    <cfqueryparam cfsqltype="cf_sql_blob"
                                value="#FileReadBinary(variables.filelocation & ii)#">);
        
        </cfquery>
        </cfif>
      </cfloop>
</cfif>
</cfif>
<form method="post" action="index.cfm" enctype="multipart/form-data">
<cfoutput>
<cfloop from="1" to="3" index="ii">
	<INPUT TYPE="text" NAME="FileDescription#ii#" id="FileDescription#ii#" style="width:400px;">
	<INPUT TYPE="FILE" NAME="AttachFile#ii#" id="AttachFile#ii#" onchange="return validateFileExtension(this);"
		class="file" style="width:400px;">
	<input type="button" value="Delete" name="DeleteFile#ii#" id="DeleteFile#ii#"
		style="height:20px;float:right;margin-right:87px;" 
		onclick="clearFile('AttachFile' + #ii#,'FileDescription' + #ii# );" />
	<br /><br />
</cfloop>
</cfoutput>
 <input type="submit" name="submit" value="Submit">
</form>

<script>
function openWindow(filename,id) {
	window.location.href = "download.cfm?ID=" + id + "&file=" + filename;
}
</script>
<cfquery name = "QGetFile">
    select UploadedFile,uploadedasbinary from files
    where Status = 1 and IssueID = <cfqueryparam cfsqltype="cf_sql_numeric" value="#url.ID#">
</cfquery>

<cfsetting enablecfoutputonly="yes">
<CFIF isDefined("QGetFile") and QGetFile.RecordCount gt 0>
  <cfoutput query="QGetFile">
    <cfset convertfile =  #tostring(tobinary(QGetFile.UploadedFile))#>
    <cfset stringfile = #tostring(QGetFile.uploadedasbinary)#>
           <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(convertfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>
           <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(stringfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>
    </cfoutput>
</CFIF>
<cfif isDefined('url.file') and url.file neq ''>
  <cfcontent type="application/x-unknown">
  <cfheader name="Content-disposition" value="attachment;filename=#url.file#">
  <cfcontent type="application/msword" deletefile="no" file = "#url.file#">
</cfif>
                                                
CREATE TABLE IF NOT EXISTS `files` (
  `fileID` int(11) NOT NULL AUTO_INCREMENT,
  `issueID` int(11) DEFAULT NULL,
  `filename` varchar(255) DEFAULT NULL,
  `uploadedfile` longtext,
  `status` int(11) NOT NULL,
  `createddate` datetime NOT NULL,
  `uploadedasbinary` longblob NOT NULL,
  PRIMARY KEY (`fileID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

Open in new window


Follow this tute to download the file

http://www.bennadel.com/blog/1274-Ask-Ben-Streaming-Binary-Data-From-The-Database-BLOB-To-The-User-Using-ColdFusion.htm
0
 

Author Comment

by:lulu50
ID: 39988419
myselfrandhawa,

I did.  

I thought you forgot about me.

please, don't go until I get it to work. (I need your help)

I'll try it right now and let you know
0
TCP/IP Network Protocol Cheat Sheet

TCP/IP is a set of network protocols which is best known for connecting the machines that make up the Internet. The truth is that TCP/IP is one of the oldest network protocols and its survival is mainly based on its simplicity and universality.

 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39988528
Ok, I am ready to help and i really want to sort your issue, try the codes given by me in your previous question and here also, we might get some solution to this or we can get some hint to proceed ahead
0
 

Author Comment

by:lulu50
ID: 39988607
Thank you myselfrandhawa

few things:

1. for the company security reason I can't access this link to see the example:
http://www.bennadel.com/blog/1274-Ask-Ben-Streaming-Binary-Data-From-The-Database-BLOB-To-The-User-Using-ColdFusion.htm

2. I am using SQL 2008 so, this is how I have the data structure. Can't use (longblob, longtext)
 
data

so, I am able to insert the file correctly in the database

datainput
 INSERT INTO Files
                        (FileName,UploadedFile,IssueID,Status,CreatedDate,uploadedasbinary)
                  VALUES
                        ( 
                        <cfif #variables["Descp" & cnt]# neq ''>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["Descp" & cnt]#">, 
                        <cfelse>
                        <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#variables["FileName" & cnt]#">, 
                        </cfif>
                        <cfqueryparam cfsqltype="cf_sql_longvarchar"
                                value="#ToBase64(variables.filelocation & ii)#">,
                    #IssueIDVal#, 
                    1, 
                    <cfqueryparam cfsqltype="cf_sql_date" value="#Now()#" /> ,
                    <cfqueryparam cfsqltype="cf_sql_blob"
                                value="#FileReadBinary(variables.filelocation & ii)#"> )    

Open in new window



3. on the view page I see doc4.doc that's the document that I uploaded to the database
when I click on it I get this error.

error


<cfquery name = "QGetFile" datasource='#strDSN#' username='#strUID#' password='#strPWD#' result="r">
    select UploadedFile,uploadedasbinary from files
    where Status = 1 and IssueID = <cfqueryparam cfsqltype="cf_sql_numeric" value="#url.ID#">
</cfquery>

<cfsetting enablecfoutputonly="yes">
<CFIF isDefined("QGetFile") and QGetFile.RecordCount gt 0>
  <cfoutput query="QGetFile">
    <cfset convertfile =  #tostring(tobinary(QGetFile.UploadedFile))#>
    <cfset stringfile = #tostring(QGetFile.uploadedasbinary)#>
           <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(convertfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>
           <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(stringfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>
    </cfoutput>
</CFIF>
<cfif isDefined('url.file') and url.file neq ''>
  <cfcontent type="application/x-unknown">
  <cfheader name="Content-disposition" value="attachment;filename=#url.file#">
  <cfcontent type="application/msword" deletefile="no" file = "#url.file#">
</cfif>
           

Open in new window

0
 

Author Comment

by:lulu50
ID: 39988652
I comment this line and tried to debug it

 <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(convertfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

       <!---  <a href="javascript:void(0);" onclick="openWindow('#jsstringformat(stringfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br> --->

Open in new window


this is the output that I am getting:

   <a href="javascript:void(0);" onclick="openWindow('D:\\inetpub\\wwwroot-dev\\mpdb\\Impact\\UploadedFiles\\doc4.doc','246')">doc4.doc</a><br>

but I think it should be like this:

   <a href="javascript:void(0);" onclick="openWindow('http://budv/mpdb/impact/ViewLogEntry.cfm/UploadedFiles/doc4.doc','246')">doc4.doc</a><br>

Open in new window

0
 

Author Comment

by:lulu50
ID: 39988676
oh
I see it myselfrandhawa

it should be like this

http://budv/mpdb/impact/UploadedFiles/doc4.doc
0
 

Author Comment

by:lulu50
ID: 39988682
so, how can I make this

<a href="javascript:void(0);" onclick="openWindow('http://budv/mpdb/impact/ViewLogEntry.cfm/UploadedFiles/doc4.doc','246')">doc4.doc</a><br>

to this


<a href="javascript:void(0);" onclick="openWindow('http://budv/mpdb/impact/UploadedFiles/doc4.doc','246')">doc4.doc</a><br>

I can keep this static and just get the file name from the database something like this.
http://budv/mpdb/impact/UploadedFiles/ + #ListLast(convertfile,'\')#
0
 

Author Comment

by:lulu50
ID: 39988703
are you with me?

Please, tell me what I am doing wrong

I see the file when I run this url it ask me for either to open it or save it 

http://budv/mpdb/impact/UploadedFiles/doc4.doc

so,

I changed my code to this: 

 <a href="javascript:void(0);" onclick="openWindow('http://budv/mpdb/impact/UploadedFiles/' + #ListLast(convertfile,'\')#,'#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

but I am getting an error says: 
  'doc4' is undefined

not sure what I am doing wrong

Open in new window

0
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39988793
Hi, You are on right path..

to do the following, there are two things you can do for this:

<a href="javascript:void(0);" onclick="openWindow('http://budv/mpdb/impact/UploadedFiles/' + #ListLast(convertfile,'\')#,'#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

Open in new window


to

<a href="javascript:void(0);" onclick="openWindow('#ListLast(convertfile,'\')#,'#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

Open in new window


and then in your cfcontent tag use the following format:

<cfcontent type="application/msword" deletefile="no" file = "#ExpandPath('UploadedFiles/#url.file#')#">

Open in new window

0
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39988798
Other thing is as i showed you, You can actually use the jsstringformat function in :

<a href="javascript:void(0);" onclick="openWindow('#jsstringformat(convertfile)#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

Open in new window


the in cfcontent:

<cfcontent type="application/msword" deletefile="no" file = "#url.file#">

Open in new window

0
 

Author Comment

by:lulu50
ID: 39988850
I made the changes and I get this error:

error

<cfquery name = "QGetFile" datasource='#strDSN#' username='#strUID#' password='#strPWD#' result="r">
    select UploadedFile,uploadedasbinary from files
    where Status = 1 and IssueID = <cfqueryparam cfsqltype="cf_sql_numeric" value="#url.ID#">
</cfquery>

<cfsetting enablecfoutputonly="yes">
<CFIF isDefined("QGetFile") and QGetFile.RecordCount gt 0>
  <cfoutput query="QGetFile">
    <cfset convertfile =  #tostring(tobinary(QGetFile.UploadedFile))#>
    <cfset fileName = #ListLast(convertfile,'\')#>
    <cfset stringfile = #tostring(QGetFile.uploadedasbinary)#>
    
<a href="javascript:void(0);" onclick="openWindow('#ListLast(convertfile,'\')#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

    </cfoutput>
</CFIF>
<cfif isDefined('url.file') and url.file neq ''>
  <cfcontent type="application/x-unknown">
  <cfheader name="Content-disposition" value="attachment;filename=#url.file#">
<cfcontent type="application/msword" deletefile="no" file = "#ExpandPath('UploadedFiles/#url.file#')#">
</cfif>
         

Open in new window



but if I do this:


  <a href="javascript:void(0);" onclick="window.open('http://budv/mpdb/impact/UploadedFiles/#fileName#')" >#ListLast(convertfile,'\')#</a>

I get what I want but is there a way not to open a new window

file
0
 

Author Comment

by:lulu50
ID: 39988899
the file that I am on is called ViewLogEntry.cfm
and the folder that I have the document in called UploadedFiles
0
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39988912
If you want to open a new window

do this:
<script>
function openWindow(filename,id) {
	window.open("download.cfm?ID=" + id + "&file=" + filename,"_blank","toolbar=yes, scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
}
</script>

<cfquery name = "QGetFile" datasource='#strDSN#' username='#strUID#' password='#strPWD#' result="r">
    select UploadedFile,uploadedasbinary from files
    where Status = 1 and IssueID = <cfqueryparam cfsqltype="cf_sql_numeric" value="#url.ID#">
</cfquery>

<cfsetting enablecfoutputonly="yes">
<CFIF isDefined("QGetFile") and QGetFile.RecordCount gt 0>
  <cfoutput query="QGetFile">
    <cfset convertfile =  #tostring(tobinary(QGetFile.UploadedFile))#>
    <cfset fileName = #ListLast(convertfile,'\')#>
    <cfset stringfile = #tostring(QGetFile.uploadedasbinary)#>
    
<a href="javascript:void(0);" onclick="openWindow('#ListLast(convertfile,'\')#','#URL.ID#')">#ListLast(convertfile,'\')#</a><br>

    </cfoutput>
</CFIF>

Open in new window


new file: download.cfm
<cfif isDefined('url.file') and url.file neq ''>
  <cfcontent type="application/x-unknown">
  <cfheader name="Content-disposition" value="attachment;filename=#url.file#">
<cfcontent type="application/msword" deletefile="no" file = "#ExpandPath('UploadedFiles/#url.file#')#">
</cfif>

Open in new window

0
 
LVL 16

Accepted Solution

by:
Gurpreet Singh Randhawa earned 2000 total points
ID: 39988915
ignore my above post:

<a href="javascript:void(0);" onclick="window.open('http://budv/mpdb/impact/UploadedFiles/#fileName#')" >#ListLast(convertfile,'\')#</a>

Open in new window


use this:

<a href="javascript:void(0);" onclick="openMe('http://budv/mpdb/impact/UploadedFiles/#fileName#')" >#ListLast(convertfile,'\')#</a>

<script>
function openMe(url) {
location.href = "ViewLogEntry.cfm?file=" + url;
}
</script>

Open in new window


under the same file viewLogEntry.cfm

post at the bottom:
<cfif isDefined('url.file') and url.file neq ''>
  <cfcontent type="application/x-unknown">
  <cfheader name="Content-disposition" value="attachment;filename=#url.file#">
<cfcontent type="application/msword" deletefile="no" file = "#ExpandPath('UploadedFiles/#url.file#')#">
</cfif>

Open in new window

0
 

Author Comment

by:lulu50
ID: 39988936
I got it!!!!!

myselfrandhawa  sorry for any confusion

I don't want to open a new window.

this is all I need

 <a href="UploadedFiles/#fileName#" >#ListLast(convertfile,'\')#</a>

it works!!!! I am happy this is what I am looking for!!!!!!!!

Thank you so much for all your help on this
0
 

Author Closing Comment

by:lulu50
ID: 39988942
Thank you for all your help!!!!

could not have done it without you thank you again
0
 
LVL 16

Expert Comment

by:Gurpreet Singh Randhawa
ID: 39988950
I am glad that it all worked out for you so well

Cheers and Happy Coding
0

Featured Post

Create CentOS 7 Newton Packstack Running Keystone

A bug was filed against RDO for the installation of Keystone v3. This guide is designed to walk you through the configuration for using Keystone v3 with Packstack. You will accomplish this using various repos and the Answers file.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article  is about submitting  form through  ColdFusion.Ajax.submitForm to the action page and send a response back in JSON format which later can be decoded using ColdFusion.JSON.decode. By this way you can avoid the usual page refresh for subm…
Sometimes databases have MILLIONS of records and we need a way to quickly query that table to return the results me need. Sure you could use CFQUERY but it takes too long when there are millions of records. That is why SOLR was invented. Please …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question