Skip to content

Instantly share code, notes, and snippets.

@dimsis
Forked from jsteenkamp/upload.cfc
Created October 5, 2012 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dimsis/3839076 to your computer and use it in GitHub Desktop.
Save dimsis/3839076 to your computer and use it in GitHub Desktop.
ColdFusion 8 code for Plupload file uploading including chunked transfers
<!--- coldfusion 8 version --->
<cfcomponent>
<cffunction name="plupload" access="remote" returntype="struct" returnformat="json" output="false">
<cfargument name="name" default="" />
<cfscript>
var uploadDir = expandPath('../assets/');
var uploadFile = uploadDir & arguments.NAME;
var response = {result = arguments.NAME, id = 0};
var result = {};
// if chunked append chunk number to filename for reassembly
if (structKeyExists(arguments, 'CHUNKS')){
uploadFile = uploadFile & '.' & arguments.CHUNK;
response.id = arguments.CHUNK;
}
</cfscript>
<!--- save file data from multi-part form.FILE --->
<cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="makeunique"/>
<cfscript>
// Example: you can return uploaded file data to client
response['size'] = result.fileSize;
response['type'] = result.contentType;
response['saved'] = result.fileWasSaved;
// reassemble chunked file
if (structKeyExists(arguments, 'CHUNKS') AND arguments.CHUNK + 1 EQ arguments.CHUNKS){
try {
uploadFile = uploadDir & arguments.NAME; // file name for reassembled file - if using a temp directory then this should be the final output path/file
if (fileExists(uploadFile)){
fileDelete(uploadFile); // delete otherwise append will add chunks to an existing file
}
tempFile = fileOpen(uploadFile,'append');
for ( i = 0; i lt arguments.CHUNKS; i++) {
chunk = fileReadBinary('#uploadDir#/#arguments.NAME#.#i#');
fileDelete('#uploadDir#/#arguments.NAME#.#i#');
fileWrite(tempFile, chunk);
}
fileClose(tempFile);
}
catch(any err){
// clean up chunks for incomplete upload
d = directoryList(uploadDir,false,'name');
if (arrayLen(d) != 0){
for (i = 1; i lte arrayLen(d); i++){
if (listFirst(d[i]) == arguments.NAME && val(listLast(d[i])) != 0){
fileDelete('#uploadDir##d[i]#');
}
}
}
// you could add more error handling and return info from err
response = {};
response.error = {code = 500, message = 'Internal Server Error'};
response.id = 0;
//respons = {'code' = 500, 'message' = 'Internal Server Error'}, 'id' = 0};
}
}
return response;
</cfscript>
</cffunction>
</cfcomponent>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment