Hi all,
目前在前端上傳檔案時打算分段上傳, 前端程式碼參考這裡, 後端部分不曉得該如何結合到目前的code, 大致想法是分段取得, 再一起寫入檔案, 但let formData = req.body.fileUpload;
會有錯誤, 請問資料型態該如何處理?
前端:
function FileChunky(file, chunkIndex){
let chunkSize = 1024 * 4 ;
let totalSize = file.size;
let totalChunkSize = Math.floor((totalSize + chunkSize - 1) / chunkSize);
if (chunkIndex >= totalChunkSize)
return;
let start = chunkIndex * chunkSize;
let blob = file.slice(start, start + chunkSize);
console.log(typeof(blob));
var formData = new FormData();
formData.append('MyFile', file);
formData.append("fileUpload", blob);
formData.append("chunkIndex", chunkIndex);
formData.append("totalSize", totalSize);
$.ajax({
url: '/fileupload/upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(){
}
});
}
後端:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb){
cb(null, './uploads')
},
filename: function (req, file, cb){
cb(null, Date.now() + file.originalname)
}
});
var upload = multer({storage: storage});
router.post('/upload', upload.single('MyFile'), function (req, res, next) {
var file = req.file;
// combine file
let formData = req.body.fileUpload;
const str_success = '{"success": true, "data":{}}';
var resobj = JSON.parse(str_success);
res.status(200).send(resobj);
});