本篇文章主要介绍了 node.js 文件上传重命名以及移动位置的示例代码, 小编觉得挺不错的, 现在分享给大家, 也给大家做个参考一起跟随小编过来看看吧
一个关于 node 上传文件的例子, 下面是前端代码,
- doUpload() {
- var formData = new FormData($("#uploadForm")[0]);
- $.ajax({
- url: 'http://localhost:3011/upload',
- type: 'POST',
- data: formData,
- async: false,
- cache: false,
- contentType: false,
- processData: false,
- success: function(returndata) {
- alert(returndata);
- },
- error: function(returndata) {
- // alert(returndata);
- }
- });
- } < form id = "uploadForm" >
<p > 上传文件:
- <input id="UpImage" type="file" name="file"/>
- <input id="text" type="text" name="text" value="232323"/>
- </p>
- <input type="button" value="上传" onClick={this.doUpload.bind(this)}/>
- <input type="button" onClick={()=>{this.submit()}} value="确定"/>
- </form>
服务端 代码 需要安装插件 formidable
- exports.upload = function (req,res,next) {
- //keepExtensions 为 true 时, 显示文件扩展名
- var form = new formidable.IncomingForm({keepExtensions:true});
- // 指定文件目录
- form.uploadDir = path.join(__dirname);
- form.parse(req,function (err,fields,files) {
- //fields 存放的为 json 数据
- //files 存放的是文件信息
- // 更改文件目录, 并且显示上传之前的名字
- fs.rename(files.file.path,__dirname+'/'+files.file.name,function (a,b) {
- });
- res.json({success:'修改成功'})
- });
- };
来源: http://www.phperz.com/article/18/0213/362909.html