node.js 通过ajax上传图片
node.js 通过ajax上传图片
这个阶段,利用晚上剩余的时间用node.js+mongdb+express+jade去实现自己的一个博客网站,里面的发表博客中需要用到上传图片,嵌入到自己用textarea标签实现的markdown编辑器中。这部分实现是利用了html5的formData函数去实现html代码(jade):
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>form#uploadfile</li><li>div.form-group</li><li>input#inputfile(type="file" name="inputfile")</li><li>p.help-block#upfiletip 只支持png和ipg格式的图片上传</li><li>button.btn.btn-success(type="button" onclick="upFile()") 上传</li></ol>
ajax代码(javascript):
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>//判断图片的格式是否是png/ipg的格式<br /> </li><li>function judgePhotoExt(name){<br /></li><li>if(name.length === 0){<br /></li><li>$("#upfiletip").css("color","red");<br /></li><li>$("#upfiletip").text = "你没有选择任何图片!!!"<br /></li><li>return false;<br /></li><li>}<br /></li><li>var extName = name.substring(name.lastIndexOf('.'),name.length).toLowerCase();<br /></li><li>if(extName != '.png' && extName != '.ipg'){<br /></li><li>$("#upfiletip").css("color","red");<br /></li><li>$("#upfiletip").text = "只支持png和ipg格式的格式的文件!!!"<br /></li><li>return false;<br /></li><li>}<br /></li><li>return true;<br /></li><li>}<br /></li><li><br /></li><li>//上传图片文件<br /></li><li>function upFile(){<br /></li><li>var filename = $("#inputfile").val();<br /></li><li>if(judgePhotoExt(filename)){<br /></li><li>var data = new FormData(); </li><li> var files = $("#inputfile")[0].files;<br /></li><li>if(files){<br /></li><li> data.append("file", files[0]);<br /></li><li>}<br /></li><li>$.ajax({<br /></li><li>url: '/blog/photo/new',<br /></li><li>type: 'POST',<br /></li><li>data: data,<br /></li><li>async: false,<br /></li><li>cache: false,<br /></li><li>contentType: false,<br /></li><li>processData: false,<br /></li><li>success: function(data){<br /></li><li>var text = $("#content-textarea").val();<br /></li><li>text = text+"";<br /></li><li>$("#content-textarea").val(text);<br /></li><li>$('#imageModal').modal('hide');<br /></li><li>},<br /></li><li>error: function(err){<br /></li><li>console.log(err);<br /></li><li>}<br /></li><li>})<br /></li><li>}<br /></li><li>} </li></ol>
对于FormData对象,你可以先创建一个空的FormData对象,然后使用append()方法向该对象里添加字段(引用别的网站的描述)
比如:
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>var oMyForm = new FormData();<br /> </li><li><br /></li><li>oMyForm.append("username", "Groucho");<br /></li><li>oMyForm.append("accountnum", 123456); // 数字123456被立即转换成字符串"123456"<br /></li><li><br /></li><li>// fileInputElement中已经包含了用户所选择的文件<br /></li><li>oMyForm.append("userfile", fileInputElement.files[0]);<br /></li><li><br /></li><li>var oFileBody = "<a id="a"><b id="b">hey!"; // Blob对象包含的文件内容<br /></li><li>var oBlob = new Blob([oFileBody], { type: "text/xml"});<br /></li><li><br /></li><li>oMyForm.append("webmasterfile", oBlob);<br /></li><li><br /></li><li>var oReq = new XMLHttpRequest();<br /></li><li>oReq.open("POST", "http://foo.com/submitform.php");<br /></li><li>oReq.send(oMyForm); </li></ol>
node.js后台代码如下:
<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>router.post('/photo/new',function(req,res,next){<br /> </li><li>let form = new formidable.IncomingForm(); //创建上传表单<br /></li><li>form.uploadDir = UPLOAD_PATH;<br /></li><li>form.keepExtensions = true; //保留后缀<br /></li><li>form.maxFieldsSize = 4*1024*1024; //文件大小<br /></li><li>form.parse(req,function(err,fields,files){<br /></li><li>if(err){<br /></li><li>res.send("插入标签失败");<br /></li><li>return;<br /></li><li>}<br /></li><li>let extName = '';<br /></li><li>let urls = [];<br /></li><li>for(var key in files){<br /></li><li>let file = files[key];<br /></li><li>switch(file.type){<br /></li><li>case 'image/pjpeg':<br /></li><li>extName = 'jpg';<br /></li><li>break;<br /></li><li>case 'image/jpeg':<br /></li><li>extName = 'jpg';<br /></li><li>break;<br /></li><li>case 'image/png':<br /></li><li>extName = 'png';<br /></li><li>case 'image/x-png':<br /></li><li>extName = 'png';<br /></li><li>break;<br /></li><li>}<br /></li><li>if(extName.length === 0){<br /></li><li>res.send("只支持png和jpg格式的图片文件");<br /></li><li>return;<br /></li><li>}<br /></li><li>let saveName = uuid.v1()+'.'+extName;<br /></li><li>let savePath = form.uploadDir+saveName;<br /></li><li>urls.push(PHOTO_URL+saveName);<br /></li><li>fs.renameSync(file.path,savePath);<br /></li><li>}<br /></li><li>res.send(urls[0]);<br /></li><li>})<br /></li><li>}) </li></ol>
使用formidable库辅助实现
其实里面最重要的还是FormData的使用,用html5实现这部分的异步上传还是比较方便的

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Motorola has released countless devices this year, although only two of them are foldables. For context, while most of the world has received the pair as the Razr 50 and Razr 50 Ultra, Motorola offers them in North America as the Razr 2024 and Razr 2

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of
