页面ajax写法
var data = new FormData(); var files = $("#idFile")[0].files; if(files){ data.append("file",files[0]); data.append("CompanyPicAddress",""); data.append("CompanyNameCN",$('#CompanyNameCN').textBox("getValue")); data.append("CompanyNameEN",$('#CompanyNameEN').textBox("getValue")); } $.ajax({ type: 'post',dataType: 'json',url:'...',data : data,contentType: false,processData: false,success : function (data,textStatus){ },error:function(XMLHttpRequest,textStatus,errorThrown){ } });
后台存储:
var fs = require('fs'); var formidable = require("formidable"); var form = new formidable.IncomingForm(); form.uploadDir = global.yjGlobal.config.routeDirs[2].rootDir+"\\client\\companyPic\\"; form.parse(sender.req,function(error,fields,files){ var fName = (new Date()).getTime(); var file = files.file<span style="font-family: Arial,Helvetica,sans-serif;">; //只上传一张图片 </span>
switch (file.type){ case "image/jpeg": fName = fName + ".jpg"; break; case "image/png": fName = fName + ".png"; break; default : fName =fName + ".png"; break; } var uploadDir = "\\client\\companyPic\\" + fName; sender.req.query=fields; sender.req.query.CompanyPicAddress="\\companyPic\\" + fName; try{ fs.renameSync(file.path,uploadDir); }catch(e){ console.log(e); } });需要注意的是from.uploadDir和uploadDir地址的赋值
1.保证目录一定存在。如果form.uploadDir不赋值,它默认的位置是C:\User\用户名\AppData\Local\Temp,一般都是将文件存储到指定位置,故这个地址是要改的
2.目录一致。rom.uploadDir和uploadDir目录一致。
页面实现:
$("#preview")[0].src=“...”//通过URL,根据自己情况直接读取地址
原文链接:https://www.f2er.com/ajax/163757.html