前端代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片上传</title>
</head>
<body>
<form action="http://localhost:3000/api/upload" method="post" enctype="multipart/form-data">
<div onclick='chooseImg()'>上传</div>
<p style="display:none;"><input id="uploadInput" type="file" name="file" onchange="updateUploadImg(this);" accept="image/gif, image/jpeg,image/jpg,image/png" multiple>
</p>
<input type="text" name="text" value="123124">
<p><input type="submit" value="Send file"></p>
</form>
<div onclick="submit()">
js提交
</div>
</body>
<script type="text/javascript">
function chooseImg() {
document.getElementById('uploadInput').click()
}
function updateUploadImg(el) {
var files = el.files
for (let i = 0; i < files.length; i++) {
const file = files[i]
if (!file.type.startsWith('image/')) {
continue
}
const img = document.createElement("img")
img.file = file;
img.src = getObjectURL(file)
document.body.appendChild(img)
}
}
function getObjectURL(file) {
var url = null
if (window.createObjectURL != undefined) { //basic
url = window.createObjectURL(file)
} else if (window.URL != undefined) { //mozilla(firefox)兼容火狐
url = window.URL.createObjectURL(file)
} else if (window.webkitURL != undefined) { //webkit or chrome
url = window.webkitURL.createObjectURL(file)
}
return url
}
function submit() {
var xhr = XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject
var fd = new FormData()
var fileList = document.getElementById('uploadInput').files
if (!fileList.length) {
return
}
for (var i = 0; i < fileList.length; i++) {
fd.append('file', fileList[i])
}
fd.append('text', 12312312)
xhr.open('POST', 'http://localhost:3000/api/upload', true)
xhr.send(fd)
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(xhr.responseText); //返回值
console.log(obj);
}
}
}
</script>
</html>
下面是后端nodejs代码示例
前端上传文件,后端接收并将图片地址返回给前端
const Koa = require('koa')
const app = new Koa()
const serve = require('koa-static')
const koaBody = require('koa-body')
const {resolve}=require('path')
const cors = require('@koa/cors')
const {
initRouter
} = require('./routes')
app.use(koaBody({
multipart:true,
formidable: {
uploadDir: resolve(__dirname, 'public/uploads')
}
}))
app.use(cors())
async function start() {
initRouter(app)
app.use(serve(__dirname + '/public'))
}
start()
app.listen(3000, () => {
console.log('sever listen 3000')
})
下面是处理文件上传的路由文件
前端单个字段可以上传多张图片,多张图片是返回对象是一个数组,单张是返回是一个对象
const Router = require('koa-router')
const fs = require('fs')
const path = require('path')
const router = new Router({
prefix: '/api'
})
router.post('/upload', async (ctx, next) => {
let fileObj = {}
let files = ctx.request.files
for (let i in ctx.request.files) {
let file = ctx.request.files[i]
let isSingle = false
if (!Array.isArray(file)) {
file = [file]
isSingle = true
}
for (let j = 0; j < file.length; j++) {
let singleRes = resolveSingleFile(file[j])
if (singleRes) {
// 单个文件直接赋值
if (isSingle) {
fileObj[i] = singleRes
break
} else if (!isSingle && !fileObj[i]) { // 如果是多个文件并且fileObj[i]还没有被赋值
fileObj[i] = []
}
fileObj[i].push(singleRes)
}
}
}
ctx.body = {
status: 1,
data: fileObj
}
})
function deleteUploadFile(filepath) {
fs.unlink(filepath, function(err) {
if (err) {
console.log(err)
}
})
}
function resolveSingleFile(file) {
let fname = file.name
let fpath = file.path
let res = {}
if (file.size && file.path) {
let extArr = fname.split('.')
let ext = extArr[extArr.length - 1]
let newPath = fpath + '.' + ext
fs.renameSync(fpath, newPath)
res.name = fname
res.url = `http://localhost:3000/uploads/${ path.basename(newPath)}`
} else {
// 路径没找到直接返回
if (!file.path) {
return
}
// 文件大小为0直接删除
deleteUploadFile(file.path)
}
return res
}
module.exports = {
initRouter: function(app) {
app
.use(router.routes())
.use(router.allowedMethods())
}
}
返回格式示例
{
"status": 1,
"data": {
"file": { "name":"...","url":"..."},
"file1":[ { "name":"...","url":"..."}]
}
}