koa upload file simple processing (upload, receive, save)

Front-end file upload (two types)

(1) element UI components

<el-upload 
	class="avatar-uploader" 
	action="/api/image/upload" 
	multiple
	:show-file-list="true"
	:on-success="handleAvatarSuccess"
	:before-upload="beforeAvatarUpload">
		<img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

Note: In the action section, /api is a proxy to solve cross-domain situations, and you can also use the following wording

//html 部分
<el-upload
	class="avatar-uploader" 
	:http-request="fileChange"
	multiple
	:show-file-list="true"
	:on-success="handleAvatarSuccess"
	:before-upload="beforeAvatarUpload">
	<img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
	<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
//js
fileChange(files) {
    
    
	console.log(files.file)
	let form = new FormData();
	form.append('file', files.file);
	//该方法为axios封装方法				
	imageUpload(form).then(res => {
    
    

	})				
}
//axios封装方法详细部分
import request from '../utills/axios.js'

export function imageUpload(file) {
    
    
  return request({
    
      	
    url: '/image/upload',
    headers: {
    
    'Content-Type': 'multipart/form-data'},
    method: 'post',
    data:file
  })
}

(Two) native

//html 部分
<input type="file" multiple="multiple" @change="fileChange" placeholder="上传文件">
//js
fileChange() {
    
    
				
				let fileList = event.target.files;			
				let file = fileList[0];
				let form = new FormData();
				form.append('file',file);				
				//你的post接口,formData方式发送
				imageUpload(form).then(res => {
    
    

				})
				
			}

Backend file configuration

add to the app.js file


const koaBody = require('koa-body');

app.use(koaBody({
    
    
	multipart: true,
	formidable: {
    
    
		//上传文件存储目录
		uploadDir:  path.join(__dirname, `/public/uploads/`),
		//允许保留后缀名
		keepExtensions: true,
		multipart: true,
	}
  })
)

Routing file section

router.post('/upload', async (ctx, next) => {
    
    
	var str=ctx.request.files.file.path
	var pathArr=str.split("\\uploads\\")
	var basicUrl="http://localhost:3001/" //为基础路径
	console.log(pathArr)
	ctx.body = {
    
    
		// filename: ctx.request.files.file,
		path:basicUrl+'uploads/'+pathArr[1]
	}
})

Looking up information on the Internet, most of the image files are processed by koa-multer.
I also tried to configure it, but it always does not work. It is still in the pit. The specific configuration is as follows
. Create a new file upload.js in the utils directory.

const multer = require('koa-multer')

//配置
var storage = multer.diskStorage({
    
    
	
    destination: function (req, file, cb) {
    
    
        cb(null, 'public/uploads'); //配置图片上传的目录
    },
	filename: function (ctx,file,cb) {
    
    
		console.log('修改文件名')
		const filenameArr = file.originalname.split('.');
		cb(null,Date.now() + '.' + filenameArr[filenameArr.length-1]);
	}
})
console.log(storage)
//加载配置
var upload = multer({
    
    storage})

module.exports = upload

Used in routing

const koaRouter = require('koa-router');
const upload = require('../utils/upload')

router.post('/upload', upload.single('file'), async (ctx, next) => {
    
    
ctx.body = {
    
    
	filename: ctx.request.files.file,
} 
 })

add to the app.js file


const koaBody = require('koa-body');

app.use(koaBody({
    
    
	multipart: true,	
  })
)

After running, the upload can be successful, and there is a return value, but no file is saved to the local directory and the upload.js path is imported correctly, but the name of the modified file cannot be printed after printing. Welcome friends who know about it.

Guess you like

Origin blog.csdn.net/qq_40969782/article/details/113998084