koa2:通过Ajax方式上传文件,使用FormData进行Ajax请求

     koa2通过表单上传的网上很多,但通过Ajax方式上传文件,使用FormData进行Ajax请求,不好找。

     参考了这个用base64上传图片的例子。https://github.com/Yuki-Minakami/Koa2-FormData

    我的项目列表。

     

 

     index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
            crossorigin="anonymous">
    </script>
</head>
<body>
<div style="margin-top: 1%;">
    <input type="file" id="uploadingfile">
    <br/><br/>
    <button id="subbtn">提交</button>
    <script>
        $(function () {
            $("#subbtn").on("click",function () {
                let data = new FormData();
                data.append("file",document.getElementById('uploadingfile').files[0]);
                data.append("info","附带信息");
                $.ajax({
                    url : "/uploadimgs",
                    type : "POST",
                    processData: false,
                    contentType: false,
                    data : data,
                    success : function(data){
                        console.log(data);
                    }
                });
            });
        })
    </script>
</div>
</body>
</html>

app.js

const Koa = require("koa");
const router = require("koa-router")();
const multiparty = require("multiparty");
const app = new Koa();
app.use(router.routes());
router.get("/",(ctx)=>{
    ctx.body = require("fs").readFileSync("./index.html","utf-8");
});
let form = new multiparty.Form({uploadDir:'./images/' });
router.post('/uploadimgs',async (ctx) => {
    async function loadimg() {
        await form.parse(ctx.req,function(err,fields,files){
            if(err){throw err; return;}
            console.log(fields);//除文件外的其他附带信息
            console.log(files);//文件信息
            return ;
        });
    }
    await loadimg().then(v=>{
        ctx.body="上传成功";
    });
});
app.listen(3000);
console.log("listen on 3000");

       上面的app.js没做任何判断,就直接报成功,感觉不好,所以完善一下。

修改后的app.js

const Koa = require("koa");
const router = require("koa-router")();
const multiparty = require("multiparty");
const app = new Koa();
app.use(router.routes());
router.get("/",(ctx)=>{
    ctx.body = require("fs").readFileSync("./index.html","utf-8");
});

router.post('/uploadimgs',async (ctx) => {
    let errsign={status:500,exception:null};
    let datasign={status:200,recordset:null};
    function loadimg() {
        let send_json={};
        return  new Promise((resolve,reject)=>{
        	let form = new multiparty.Form({uploadDir:'./images/' });
            form.parse(ctx.req,function(err,fields,files){
                if(err){
                    // throw err;
                    console.log(err);//Error: write after end
                    send_json={
                        exception:"解析失败",
                        err:false
                    };
                    resolve(send_json);
                    // return send_json;
                }else{
                    // console.log(fields);//除文件外的其他附带信息
                    // console.log("files = ",files);//文件信息
                    if(files!==undefined&&files!=={}&&files.file!==undefined){
                        // console.log(files.file);
                        if(files.file.length>0){
                            let filename = files.file[0].path;
                            let filetype = files.file[0].headers['content-type'];
                            let realname = files.file[0].originalFilename;
                            // console.log("filename = ",filename);
                            // console.log("filetype = ",filetype);
                            // console.log("realname = ",realname);
                            if(filetype.indexOf("image/")>=0){
                                send_json={
                                    recordset:"上传成功",
                                    err:true
                                };
                                resolve(send_json);
                            }else{
                                send_json={
                                    exception:"上传失败",
                                    err:false
                                };
                                fs.unlinkSync(filename);//删除非图片文件
                                resolve(send_json);
                            }
                        }
                    }else{
                        send_json={
                            exception:"未上传文件",
                            err:false
                        };
                        resolve(send_json);
                    }
                }
            });
        });
    }
    await loadimg().then(r=>{
        // console.log("r = ",r);
        if(r.err===false){
            errsign["exception"]=r.exception;
            ctx.body=errsign;
        }else{
            datasign["recordset"]=r.recordset;
            ctx.body=datasign;
        }
    });
});
app.listen(3030);
console.log("listen on 3030");

  

 

posted @ 2018-04-19 09:39  赤羽飞鸿  阅读(4481)  评论(3编辑  收藏  举报