Solved

File download

Posted on 2014-04-08
18
259 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
  • 10
  • 8
18 Comments
 
LVL 15

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 15

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
 
LVL 15

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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 15

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 15

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 15

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 15

Accepted Solution

by:
Gurpreet Singh Randhawa earned 500 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 15

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

PROBLEM: How to add your own buttons to the bottom toolbar with paging info ( result count ). While creating a cfgrid, I ran into an issue where I wanted to embed my own custom buttons where the default ones ( insert / delete / etc… ) are for aes…
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 …
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now