[关闭]
@lizlalala 2016-05-07T11:35:41.000000Z 字数 2080 阅读 1232

node学习——文件上传

express 文件上传


开发总结

一、upload

注意事项

1.如果是form的话

使用form表单初始化FormData对象方式上传文件

2.如果是input+ajax处理的话

要保证
(1)multer的single要与input中的name一致 == formdata中的key

  1. var upload = multer({
  2. dest:path.join(__dirname,"..","public/uploads/"),
  3. fileFilter:function(req,file,cb){
  4. var mimetype = file.mimetype.split('/')[1];
  5. console.log("filetype ",file.mimetype);
  6. /*
  7. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  8. if(mimetype !=='vnd.ms-excel' || mimetype !=='vnd.openxmlformats-officedocument.spreadsheetml.sheet' ){
  9. req.fileValidationError = '请上传excel文件';
  10. return cb(null,false,new Error("请上传excel文件"));
  11. }
  12. */
  13. cb(null,true);
  14. }}).single('excel'); //这边的single要与input中的name一致

(2)formdata的key也要与input中的name一致

  1. var form = new FormData();
  2. //attention
  3. form.append("excel",$(".inputfile").get(0).files[0]);
  4. console.log("upload file ",JSON.stringify(form));
  5. var request = $.ajax({
  6. url: '/tel/upload',
  7. method:'post',
  8. data:form,
  9. processData: false,
  10. contentType: false,
  11. cache:false,
  12. success:function(data,textStatus,jqXHR){
  13. console.log("-------",data);
  14. $(".submit").text("上传成功");
  15. console.log("---receive data "+data);
  16. },

(3) append()的第二个参数应是文件对象,即element.files[0]。
contentType也要设置为‘false’。因为上文已经声明是formdata对象了,不需要再去定义
processData也要设为false,否则jQuery会将你的formdata转为string类型。

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. >Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

(4)标签能够上传多个文件,
只需要在里添加multiple或multiple="multiple"属性。

二、

如果希望重命名的话(现在的官方文档中,只支持dest/storage、filefilter、limits,不支持其他如rename等,因此只能用diskStorage比较好)。
此时需要注意的是,如果destination是一个函数,那么目录需要是已创建好的,如果dest是传的string,那么如果不存在文件夹,multer会帮你新建。

三. node-xlsx解析

xlsx -> array of json(rows)

[{"name":"Sheet1","data":[["id","system","是否合格"],[1,"ios","是"],[2,"android","是"],[3,"wp","否"]]},
{"name":"Sheet2","data":[]},
{"name":"Sheet3","data":[]}]

todo

  1. read excel
    read exce with node
  2. rename in storage
    rename in storage

references

  1. send-formdata-and-string-data-together-through-jquery-ajax
  2. upload file and store to mongoose

toread

  1. what-does-enctype-multipart-form-data-mean
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注