图片上传前端可以采用两种方式:
- formData
- base64
下面的例子都是采用formData来上传图片的
一、前端部分
<div>
<input type="file" id="file" name="file" multiple>
<input type="submit" class="submit" value="Upload">
</div>
<script type="text/javascript">
$(".submit").on("click", function(){
var file = $("#file")[0].files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: "/api/upload",
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function(){
},
error: function(){
}
})
})
</script>
Q:为何不用form?
A:使用form提交,一般会这样写
<form action="/uploads" method="POST" enctype="multiple/form-data">
<input type="file" name="file">
</form>
这种form表单提交,会跳转页面,就算去掉action,改成dosubmits="fn();",也还是会跳转页面,具体的有时间再去研究一下。
二、后端部分
1、方式一:简单粗暴的读取图片与写入图片,没考虑图片读取与写入过程中的出错情况。
const router = require('koa-router')()
const multer = require('koa-multer')
const fs = require('fs')
const path = require('path')
const upload = multer({ dest: __dirname + '/uploads/' });
router.post('/upload', upload.single('file'), async function(ctx, next){
var file = ctx.req.file;
if (file != null) {
const reader = fs.createReadStream(file.path);
const filePath = path.join(path.resolve(__dirname, '..'), '/uploads');
const fileName = Math.random().toString(16).substr(2) + '.' + getSuffixName(file.originalname);
const uploadFilePath = path.join(filePath, fileName);
const stream = fs.createWriteStream(uploadFilePath);
reader.pipe(stream);
console.log('uploading %s -> %s', file.name, stream.path);
} else {
console.log('No upload file!');
}
ctx.body = 'upload success';
});
/**
* 获取上传文件的后缀名
* @param {string} fileName 获取上传文件的后缀名
* @return {string} 文件后缀名
*/
function getSuffixName( fileName ) {
let nameList = fileName.split('.')
return nameList[nameList.length - 1]
}
2、方式二:使用busboy
const router = require('koa-router')()
const Busboy = require('busboy')
const path = require('path')
router.post('/upload', async function(ctx, next){
var result = { success: false };
var filePath = path.join(path.resolve(__dirname, '..'), '/public/images/uploads');
result = await uploadFile(ctx, {
path: filePath
});
ctx.body = result;
});
function uploadFile(ctx, options){
var busboy = new Busboy({ headers: ctx.req.headers });
return new Promise((resolve, reject) => {
console.log("文件上传中");
var result = {
success: false,
message: '',
data: null
};
// 解析请求文件事件
busboy.on('file', function(fieldname, file, filename, encoding, mimetype){
var filePath = options.path;
var fileName = Math.random().toString(16).substr(2) + '.' + getSuffixName(filename);
var uploadPath = path.join(filePath, fileName);
//文件保存到指定目录
file.pipe(fs.createWriteStream(uploadPath));
// 文件写入事件结束
file.on('end', function() {
result.success = true;
result.message = '文件上传成功';
result.data = {
pictureUrl: `http://${ctx.host}/images/uploads/${fileName}`
}
console.log('文件上传成功!')
resolve(result)
})
});
busboy.on('finish', function() {
console.log('文件上传结束');
resolve(result);
});
busboy.on('error', function(){
console.log('文件上传出错');
reject(result);
});
ctx.req.pipe(busboy);
})
}
/**
* 获取上传文件的后缀名
* @param {string} fileName 获取上传文件的后缀名
* @return {string} 文件后缀名
*/
function getSuffixName( fileName ) {
let nameList = fileName.split('.')
return nameList[nameList.length - 1]
}
网友评论