问题
What am I doing wrong?
fileUpload.cfm
<cfcomponent name="fileAttachment" hint="This is the File Attachment Object">
<cffunction name="uploadFile" access="public" output="no" returntype="string">
<cfargument name="fileToUpload" type="string" required="no">
<cfargument name="pDsn" required="no" type="string">
<cfset var cffile = "">
<cffile action="upload" destination="D:\apache\htdocs\abc\uploads" filefield="#ARGUMENTS.fileToUpload#" nameconflict="makeunique">
<cfreturn cffile.clientFile />
</cffunction>
</cfcomponent>
test_fileUpload.cfm
<form action="fileUpload.cfm" enctype="multipart/form-data" method="post">
<input type="file" name="fileToUpload"><br/>
<input type="submit">
</form>
回答1:
This line:
<cffile action="upload" destination="D:\apache\htdocs\abc\uploads" filefield="#ARGUMENTS.fileToUpload#" nameconflict="makeunique">
The filefield attribute wants the name of the form field that will hold the uploaded file. You're on the right track, but unfortunately, that's not what the value of #ARGUMENTS.fileToUpload#
is, presently--based on your construction, it holds a reference to the actual file itself.
Add a new hidden field to your form:
<input type="hidden" name="nameOfField" value="fileToUpload">
Then, pass FORM.nameOfField
to your uploadFile() method as the first parameter. CFFILE will take care of the rest.
回答2:
Well, I found lots of issue with this code.
- fileupload.cfm should be component file fileupload.cfc as you are writing component in it.
- As you are going to call directly upload method from form call access type must be REMOTE.
- action page should change to fileupload.cfc?method=uploadFile
- if you define cffile as local variable of component then you have to specify result="cffile" attribute in cffile tag.
- filefield attribute take the name of form field not its value so just remove ## tag and just use fileToUpload.
Below is correct code. fileupload.cfc
<cffunction name="uploadFile" access="remote" output="no" returntype="string">
<cfargument name="fileToUpload" type="string" required="no">
<cfargument name="pDsn" required="no" type="string">
<cfset var cffile = "">
<cffile action="upload" destination="D:\apache\htdocs\abc\uploads" filefield="fileToUpload" result="cffile" nameconflict="makeunique">
<cfreturn cffile.clientFile />
</cffunction>
</cfcomponent>
test_fileupload.cfm
`<form action="fileupload.cfc?method=uploadFile" enctype="multipart/form-data" method="post">
<input type="file" name="fileToUpload"><br/>
<input type="submit"> </form>`
来源:https://stackoverflow.com/questions/8733270/upload-file-in-object