节点fs(文件流)在上传单个文件时创建2个文件

时间:2017-08-18 04:22:06

标签: javascript node.js fs

我使用以下代码允许用户将图像上传到服务器:

app.post("/api/upload", function (req, res) {

  fs.readFile(req.files[0].path, function (err, data) {
    console.log('The data for the file..', data);

    if (err) {
      res.send(err).end();
    } else {
      // ...
      var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname;
      fs.writeFile(newPath, data, function (err) {
        console.log('File Written');
        if (err) {
          res.send(err).end();
        } else {  
          res.send({
            success: true,
            file: newPath,
            files: req.files
          }).end();
        }
        //res.end({"success": true})
      });
    }
  });


});

问题是,对于上传的evey文件,我也得到了一个arrayBuffer版本(我认为)见图片:

enter image description here

我如何防止这种情况,最重要的是,为什么会发生这种情况? 谢谢!

3 个答案:

答案 0 :(得分:1)

有时我使用multer模块获得解决方案。使用此模块,您可以上传文件和图像。它已成功上传到目标文件夹。

这是我的服务器代码[TIME]

   Category                     GPU
   |                            Hardware
   |                            Unit
   |                            |            Throughput
   |                            |            |               Execution
   |                            |            |               Latency
   |                            |            |               |                  PTX instructions                                                      Note 
   |____________________________|____________|_______________|__________________|_____________________________________________________________________|________________________________________________________________________________________________________________________
   Load_shared                  LSU          2               +  30              ld, ldu                                                               Note, .ss = .shared ; .vec and .type determine the size of load. Note also that we omit .cop since no cacheable in Ocelot
   Load_global                  LSU          2               + 600              ld, ldu, prefetch, prefetchu                                          Note, .ss = .global; .vec and .type determine the size of load. Note, Ocelot may not generate prefetch since no caches
   Load_local                   LSU          2               + 600              ld, ldu, prefetch, prefetchu                                          Note, .ss = .local; .vec and .type determine the size of load. Note, Ocelot may not generate prefetch since no caches
   Load_const                   LSU          2               + 600              ld, ldu                                                               Note, .ss = .const; .vec and .type determine the size of load
   Load_param                   LSU          2               +  30              ld, ldu                                                               Note, .ss = .param; .vec and .type determine the size of load
   |                            |                              
   Store_shared                 LSU          2               +  30              st                                                                    Note, .ss = .shared; .vec and .type determine the size of store
   Store_global                 LSU          2               + 600              st                                                                    Note, .ss = .global; .vec and .type determine the size of store
   Store_local                  LSU          2               + 600              st                                                                    Note, .ss = .local; .vec and .type determine the size of store
   Read_modify_write_shared     LSU          2               + 600              atom, red                                                             Note, .space = shared; .type determine the size
   Read_modify_write_global     LSU          2               + 600              atom, red                                                             Note, .space = global; .type determine the size
   |                            |                              
   Texture                      LSU          2               + 600              tex, txq, suld, sust, sured, suq
   |                            |                              
   Integer                      ALU          2               +  24              add, sub, add.cc, addc, sub.cc, subc, mul, mad, mul24, mad24, sad, div, rem, abs, neg, min, max, popc, clz, bfind, brev, bfe, bfi, prmt, mov
   |                            |                                                                                                                     Note, these integer inst. with type = { .u16, .u32, .u64, .s16, .s32, .s64 };
   |                            |                              
   Float_single                 ALU          2               +  24              testp, copysign, add, sub, mul, fma, mad, div, abs, neg, min, max     Note, these Float-single inst. with type = { .f32 };
   Float_double                 ALU          1               +  48              testp, copysign, add, sub, mul, fma, mad, div, abs, neg, min, max     Note, these Float-double inst. with type = { .f64 };
   Special_single               SFU          8               +  48              rcp, sqrt, rsqrt, sin, cos, lg2, ex2                                  Note, these special-single with type = { .f32 };
   Special_double               SFU          8               +  72              rcp, sqrt, rsqrt, sin, cos, lg2, ex2                                  Note, these special-double with type = { .f64 };
   |                                                           
   Logical                      ALU          2               +  24              and, or, xor, not, cnot, shl, shr
   Control                      ALU          2               +  24              bra, call, ret, exit
   |                                                           
   Synchronization              ALU          2               +  24              bar, member, vote
   Compare & Select             ALU          2               +  24              set, setp, selp, slct
   |                                                           
   Conversion                   ALU          2               +  24              Isspacep, cvta, cvt
   Miscellanies                 ALU          2               +  24              brkpt, pmevent, trap
   Video                        ALU          2               +  24              vadd, vsub, vabsdiff, vmin, vmax, vshl, vshr, vmad, vset

创建app.js文件夹并将此var express =r equire('express'); var multer = require('multer'); var path = require('path') var app = express(); var ejs = require('ejs') app.set('view engine', 'ejs') var storage = multer.diskStorage({ destination: function(req, file, callback) { callback(null, './public/uploads')//here you can place your destination path }, filename: function(req, file, callback) { callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)) } }) app.get('/api/file',function(req,res){ res.render('index'); }); app.post('/api/file', function(req, res) { var upload = multer({ storage: storage}).single('userFile'); upload(req, res, function(err) { console.log("File uploaded"); res.end('File is uploaded') }) }) app.listen(3000,function(){ console.log("working on port 3000"); }); 文件放入其中

views

在此之后运行服务器为index.ejs。打开浏览器并在运行后输入<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form id="uploadForm" enctype="multipart/form-data" method="post"> <input type="file" name="userFile" /> <input type="submit" value="Upload File" name="submit"> </form> </body> </html> 此url选择要上传到目标文件夹的文件。并在终端和终端都有成功的响应browser.Hope这对你有帮助。

答案 1 :(得分:0)

当您使用multer等模块时,文件上传通常(永久)保存到磁盘(除非您在multer的情况下更改基础后备存储)。因此,当您阅读文件并将其写回时,您就有了副本。

如果您需要制作文件的副本,这不是最有效的解决方案,因为您正在将整个内容读入内存。在使用更高效的复制机制之前,最好先进行流式复制(使用fs.createReadStream()fs.createWriteStream())以最大限度地减少内存中的数据量。

如果您想要移动 / 重命名 multer保存到磁盘的文件,那么您可以配置multer以便您动态提供目标文件名(有可用的钩子),您可以使用fs.rename()随后移动或重命名文件。

答案 2 :(得分:0)

在我看来,您正在看到临时上传文件和保存的文件。如果添加代码来删除临时文件(req.files [0] .path),您的代码应该可以正常工作。