上传文本文件时,XHR Chunk上传有一个问题

时间:2017-09-26 13:01:54

标签: javascript jquery file-upload

我在ColdFusion项目中使用XHR块上传。除了扩展名为.txt的文件外,上传工作正常。 当我尝试上传文本文件时,它将被上传并变为空(文件大小变为0字节)。

为什么会这样?

这是我得到的例外......

An exception occurred when executing method write.The cause of this exception was that: coldfusion.runtime.Cast$NumberConversionException: The value Hello this is a test file. cannot be converted to a number..

这是我的 home.cfm

<html>
	<head>
		<title>Chunk Upload</title>
		<style type="text/css">
			.text-center{text-align: center;}
			#alert{color: red}
			#uploading, .filesize{color: red}
			#success{color: green}
		</style>
	</head>
	<body>
		<script type="text/javascript">

            var blobs = [];

            function bytesToSize(bytes) {
			   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
			   if (bytes == 0) return '0 Byte';
			   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
			   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
			};
		/*
		 * function that uploads a fragment of the file
		 */
                function uploadChunk(blob, fileName, fileType, count){
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'chunkUpload.cfm', false);
                    xhr.onload = function(e){
                    document.getElementById("success").innerHTML = "Uploading... <span class='filesize'>" + count + "</span> MB";
                    }
                    xhr.setRequestHeader('X_FILE_NAME', fileName);
                    xhr.setRequestHeader('Content-Type', fileType)
                    // document.getElementById("uploading").innerHTML += "Uploading chunk of size " + blob.size + ".<br/>";
                    xhr.send(blob);
                };
		/*
		 * Invoke this function when the submit button is clicked.
		 */
		       function uploadSubmit(){
		 	     var fileInputs = document.querySelectorAll('#userfile');
		 	     for (i = 0; i < fileInputs.length; i++) {
                  sliceFilesToFragments(fileInputs[i]);
                 }
		       };
		/*
		 * function that slice the file into 1MB fragment
		 */
		       function sliceFilesToFragments(input){
		       	    var count = 0;
		       	    var file = input.files[0];
                    // Upload 1 mb per chunk
                    var bytes_per_chunk = 1024 * 1024;
                    var start = 0;
                    var end = bytes_per_chunk;
                    var size = file.size;
                    document.getElementById("TotalSize").innerHTML += "Total File size <span class='filesize'>"+bytesToSize(size)+"</span>";
                    while (start < size) {
			        //push the fragments to an array
                        blobs.push(file.slice(start, end));
                        start = end;
                        end = start + bytes_per_chunk;
                    }
                        var blobArray = blobs.slice();
		            //upload the fragment to the server
                    while (blob = blobs.shift()) {
                    	count++;
                    	if(blobArray.length == count){
                    		count = 'File Uploaded Successfully';
                    	}
			        	uploadChunk(blob, file.name, file.type, count);
                    }
		       };

		</script>
				<h2 class="text-center">Chunk Upload using XHR & CF</h2>
		<form name="myform" method="post" enctype="multipart/form-data" >
			<pre>
				* notes *
				1) Refresh Each time, before upload
				2) Uploading 1 mb per chunk for now
				3) To see the chunks: go to Chrome > inpect element > Network tab
			</pre>
			<pre>
				Upload:<input type="file" id="userfile"><br>
			</pre>
			<pre>
				<input type="button" id="submit" value="Submit" onclick="uploadSubmit()"><br>
			</pre>
			<pre><span id="TotalSize"></span></pre><br>
			<pre><span id="success"></span></pre>
		</form>
	</body>

</html>

这是我的 chunkUpload.cfm

 <cfoutput>
	<cfset headerData = getHTTPRequestData().headers>
	<cfset content = getHTTPRequestData().content>
	<cfset filePath = expandPath("./Uploads/") & "#headerData.X_FILE_NAME#">
	<cfset fos = createObject("java", "java.io.FileOutputStream").init(filePath, true)>
	<cfset fos.write(content)>
	<cfset fos.close()>
</cfoutput>

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我的问题通过更改文件的内容类型得到解决。更新您的内容类型,如下所示

xhr.setRequestHeader('Content-Type', "application/octet-stream");