search
HomeBackend DevelopmentPHP Tutorialnode.js 通过ajax上传图片_PHP教程

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实现这部分的异步上传还是比较方便的

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1114324.htmlTechArticlenode.js 通过ajax上传图片 这个阶段,利用晚上剩余的时间用node.js+mongdb+express+jade去实现自己的一个博客网站,里面的发表博客中需要用到上传...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use