对于较大文件实现分片上传

思路:通过<input type="file" id="file" name="file" />   <input type="button" id="breakPointUploadFile" name="breakPointUploadFile" /> 获取上传的文件资源。调用Windows的分片对象File.prototype.slice。通过指定每次分片的大小,计算出分片个数。然后采用递归的方式一直上传每个分片至后台。直到上传分片数大于了总分片数时,跳出递归。具体代码如下:

前端:

<input type="file" id="file" name="file" />

<input type="button" id="breakPointUploadFile" name="breakPointUploadFile" />

js代码:

<script type="text/javascript">

//获取文件分片对象

    const blobSlice =File.prototype.slice ||File.prototype.mozSlice ||File.prototype.webkitSlice;

$(function () {

//设置每个分片大小

        const chunkSize =2 *1024 *1024;// 每个chunk的大小,2兆

        $("#breakPointUploadFile").click(function () {

//得到上传的文件资源

            const file =$('#file')[0].files[0];

// 需要分片成多少个

            const totalChunk =Math.ceil(file.size /chunkSize);

breakPointUploadFile(0,totalChunk,chunkSize,file);

});

});

/**

    * 分片上传

    * i - 第几片

    * totalChunk - 分片总数

    * chunkSize  - 每片大小

    * file 要上传的文件

    * */

    function breakPointUploadFile(i, totalChunk, chunkSize, file) {

//当前上传文件块的起始位置

            const startLength = i * chunkSize;

//当文件末尾不足一个分片时,取小者

            const endLength =Math.min(file.size,startLength + chunkSize);

var formData =new FormData();

//通过blobSlice获取分片文件

            formData.append("file",blobSlice.call(file,startLength,endLength));

formData.append("startLength",startLength);

formData.append("fileName", file.name);

$.ajax({

url:'http://localhost:8080/breakPointUploadFileDo',

dataType:'json',

type:'POST',

async:false,

data:formData,

processData:false,

contentType:false,

success:function (data) {

console.log(data);

if (data.succeed) {

i++;

//当分片上传达到总分片个数,跳出递归

                        if (i < totalChunk) {

console.log("****>" + i);

setTimeout(function () {

//采用递归调用该函数

                                breakPointUploadFile(i, totalChunk, chunkSize, file);

},0);

}else {

alert("文件上传成功");

}

}

},

error:function (response) {

console.log(response);

alert("异常")

}

});

}

</script>

代码截图:



后台代码:

@RequestMapping("breakPointUploadFileDo")

public AjaxResponse breakPointUploadFileDo(@RequestParam MultipartFile file,long startLength, String fileName) {

AjaxResponse ajaxResponse =new AjaxResponse(true,"200");

System.out.println(file +" ** " + startLength);

if (file.getSize() <=0) {

return new AjaxResponse(false,"500");

}

int len =0;

final byte[] arr =new byte[1024];

final String writeFileName ="D:/test-" + fileName;

try (RandomAccessFile writeFile =new RandomAccessFile(writeFileName,"rw")) {

writeFile.seek(startLength);

final InputStream iStream = file.getInputStream();

while ((len = iStream.read(arr)) != -1) {

writeFile.write(arr,0, len);

}

}catch (final Exception e) {

e.printStackTrace();

}

return ajaxResponse;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容