search
Homephp教程php手册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+"![图片提示]("+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>
注意:其中一定要注意的点: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>
这部分内容需要查看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>

使用formidable库辅助实现

其实里面最重要的还是FormData的使用,用html5实现这部分的异步上传还是比较方便的
Statement
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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.