Table of Contents
node.js 通过ajax上传图片
html代码(jade):
ajax代码(javascript):
node.js后台代码如下:
Home php教程 php手册 node.js 通过ajax上传图片

node.js 通过ajax上传图片

Jun 13, 2016 am 08:43 AM
android

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>
Copy after login

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+"![图片提示]("+data+")";<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>
Copy after login
注意:其中一定要注意的点:processData的属性要设置为false,这个是html5的属性,如果没有设置为false的话,这个地方会出问题。主要是文件的内容不希望转换成字符串。具体可查看jquery ajax的参数解释:http://www.w3school.com.cn/jquery/ajax_ajax.asp

对于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>
Copy after login
这部分内容需要查看FormData对象的具体内容,可查看该网址:http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html

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>
Copy after login

使用formidable库辅助实现

其实里面最重要的还是FormData的使用,用html5实现这部分的异步上传还是比较方便的
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

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

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

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

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

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

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

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

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

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 Razr 50s shows itself as possible new budget foldable in early leak Motorola Razr 50s shows itself as possible new budget foldable in early leak Sep 07, 2024 am 09:35 AM

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

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

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 Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

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

See all articles