upload, 图片上传,上传七牛为例

要达到的目的:上传一张图片返回图片url

html5自带图片上传,使用input的file

html内容:

	<input type="file" id="test-image-file" name="test" accept="image/gif, image/jpeg, image/png, image/jpg">

js内容:

	var fileInput = document.getElementById('test-image-file')  // 获取input
	var contentImg = null // 获取的图片url
	
	fileInput.addEventListener('change', function() {
		if(!fileInput.value) {
			info.innerHTML = '没有选择文件'
			return
		 }
	    var file = fileInput.files[0]
		if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
			alert('不是有效的图片文件!')
			return
		}
		
		// 转一下
		var formData = new FormData()
			formData.append("file", $(this).get(0).files[0])
		// 发送请求
		$.ajax({
			url: '/api/upload', // 填自己的路径
			type:'POST',
			data:formData,
			cache: false,
			contentType: false,
			processData: false,
			success:function(data){
				contentImg = data.payload.url
			},
			error:function(){
				console.log('图片上传失败')
			}
		})
	})

后端的处理:
我后端用的node.js

const MIME_TYPES = [
  'image/jpeg',
  'image/gif',
  'image/png'
]

const MAX_FILE_SIZE = 5 * 1024 * 1024 // 10M

module.exports = async (ctx, next) => {

  const file = ctx.req.file
  if (!file) {
    ctx.fail('file 不能为空')
    return
  }

  if (MIME_TYPES.indexOf(file.mimetype) === -1) {
    ctx.fail('文件格式错误')
    return
  }

  if (file.size > MAX_FILE_SIZE) {
    ctx.fail('上传文件必须小于5M')
    return
  }

  try {
    const url = await qiniuService.upload(file.buffer, { // qiniuService是我上传七牛的的方法
      mimetype: file.mimetype,
      ext: file.originalname.split('.').slice(-1)[0]
    })

    ctx.succeed({url}) // 成功返回url
  } catch (e) {
    ctx.handleErr(e)
  }
}

上传七牛

/**
 * 上传文件到七牛
 * @param {*} buffer 文件buffer
 * @param {*} options
 *
 * options 格式如下:
 * {
 *  ext: '', // 文件名扩展后缀
 *  key: '', // 文件名, 不传入
 *  mimeType: '' // 文件MIME类型
 * }
 *
 */
const upload = (buffer, options) => {
	
}

版权声明:本文为qq_40313245原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。