欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

dai-siki/vue-image-crop-upload 上传图片 上传图像 前端实现 有大用

A beautiful vue component for image crop and upload. (vue图片剪裁上传组件) 
JavaScriptVueCSSHTML
 
Upload filesFind file
New pull request
Latest commit 7412141 6 days ago@dai-siki  '1.3.9'

 README.md

vue-image-crop-upload

A beautiful vue component for image crop and upload. (vue图片剪裁上传组件).

** Notice: ** This component is designed for pc, not recommended for use on the mobile side.(该组件适用于pc端,不推荐手机端使用)

GitHub issues GitHub forks GitHub stars Twitter

NPM

中文文档在下面

Change log

@1.3.0

  • Added the Russian language pack (thanks @bigperson)
  • Added a new Props: "headers" (Used to set the POST request header)

@1.2.0

  • Compatible vue2

@1.1.0

  • Adjusted Props naming: "otherParams"=>"params", "langConf"=>“langExt”
  • Optimized language packs

Demo

Click me.

Screenshot

screenshot

Brower compatibility

IE10+

Env

vue@1/vue@2 + webpack + es6

Install

npm

$ npm install vue-image-crop-upload

Usage

Props

名称类型默认说明
fieldString'upload'Upload input filename, used for server side get the file stream.
valueBooleantwoWayshow or not
urlString''Server api path,like "/avatar/upload"
paramsObjectnullPOST Params,like "{k:v}"
headersObjectnullPOST request header,like "{k:v}"
langTypeString'zh'language type
langExtObject language extend
widthNumber200width of receive image
heightNumber200height of receive image
imgFormatstring'jpg'jpg/png, Server api receive file type.

Events

名称说明
cropSuccessimage crop success, params( imageDataUrl, field )
cropUploadSuccessupload success, params( jsonData, field )
cropUploadFailupload fail, params( status, field )

Language package

{
    zh: {
        hint: '点击,或拖动图片至此处',
        loading: '正在上传……',
        noSupported: '浏览器不支持该功能,请使用IE10以上或其他现在浏览器!',
        success: '上传成功',
        fail: '图片上传失败',
        preview: '头像预览',
        btn: {
            off: '取消',
            close: '关闭',
            back: '上一步',
            save: '保存'
        },
        error: {
            onlyImg: '仅限图片格式',
            outOfSize: '单文件大小不能超过 ',
            lowestPx: '图片最低像素为(宽*高):'
        }
    },
    en: {
        hint: 'Click, or drag the file here',
        loading: 'Uploading……',
        noSupported: 'Browser does not support, please use IE10+ or other browsers',
        success: 'Upload success',
        fail: 'Upload failed',
        preview: 'Preview',
        btn: {
            off: 'Cancel',
            close: 'Close',
            back: 'Back',
            save: 'Save'
        },
        error: {
            onlyImg: 'Image only',
            outOfSize: 'Image exceeds size limit: ',
            lowestPx: 'The lowest pixel in the image: '
        }
    },
	ru: {
		hint: 'Нажмите, или перетащите файл в это окно',
		loading: 'Загружаю……',
		noSupported: 'Ваш браузер не поддерживается, пожалуйста, используйте IE10 + или другие браузеры',
		success: 'Загрузка выполнена успешно',
		fail: 'Ошибка загрузки',
		preview: 'Предпросмотр',
		btn: {
			off: 'Отменить',
			close: 'Закрыть',
			back: 'Назад',
			save: 'Сохранить'
		},
		error: {
			onlyImg: 'Только изображения',
			outOfSize: 'Изображение превышает предельный размер: ',
			lowestPx: 'Минимальный размер изображения: '
		}
	}
}

Example vue@1

<div id="app">
	<a class="btn" @click="toggleShow">set avatar</a>
	<my-upload field="img"
		:width="300"
		:height="300"
		url="/upload"
		:params="params"
		:headers="headers"
        lang-type="en"
		:value.sync="show"
		img-format="png"></my-upload>
	<img :src="imgDataUrl">
</div>

<script>
	import 'babel-polyfill'; // es6 shim
	import Vue from 'vue';
	import myUpload from 'vue-image-crop-upload';

	new Vue({
		el: '#app',
		data: {
			show: true,
			params: {
				token: '123456798',
				name: 'avatar'
			},
			headers: {
				smail: '*_~'
			},
			imgDataUrl: '' // the datebase64 url of created image
		},
		components: {
			'my-upload': myUpload
		},
		methods: {
			toggleShow() {
				this.show = !this.show;
			}
		},
		events: {
			/**
			 * crop success
			 *
			 * [param] imgDataUrl
			 * [param] field
			 */
			cropSuccess(imgDataUrl, field){
				console.log('-------- crop success --------');
				this.imgDataUrl = imgDataUrl;
			},
			/**
			 * upload success
			 *
			 * [param] jsonData   server api return data, already json encode
			 * [param] field
			 */
			cropUploadSuccess(jsonData, field){
				console.log('-------- upload success --------');
				console.log(jsonData);
				console.log('field: ' + field);
			},
			/**
			 * upload fail
			 *
			 * [param] status    server api return error status, like 500
			 * [param] field
			 */
			cropUploadFail(status, field){
				console.log('-------- upload fail --------');
				console.log(status);
				console.log('field: ' + field);
			}
		}
	});

</script>

Example vue@2

<div id="app">
	<a class="btn" @click="toggleShow">set avatar</a>
	<my-upload field="img"
        @crop-success="cropSuccess"
        @crop-upload-success="cropUploadSuccess"
        @crop-upload-fail="cropUploadFail"
        v-model="show"
		:width="300"
		:height="300"
		url="/upload"
		:params="params"
		:headers="headers"
		img-format="png"></my-upload>
	<img :src="imgDataUrl">
</div>

<script>
	import 'babel-polyfill'; // es6 shim
	import Vue from 'vue';
	import myUpload from 'vue-image-crop-upload/upload-2.vue';

	new Vue({
		el: '#app',
		data: {
			show: true,
			params: {
				token: '123456798',
				name: 'avatar'
			},
			headers: {
				smail: '*_~'
			},
			imgDataUrl: '' // the datebase64 url of created image
		},
		components: {
			'my-upload': myUpload
		},
		methods: {
			toggleShow() {
				this.show = !this.show;
			},
            /**
			 * crop success
			 *
			 * [param] imgDataUrl
			 * [param] field
			 */
			cropSuccess(imgDataUrl, field){
				console.log('-------- crop success --------');
				this.imgDataUrl = imgDataUrl;
			},
			/**
			 * upload success
			 *
			 * [param] jsonData  server api return data, already json encode
			 * [param] field
			 */
			cropUploadSuccess(jsonData, field){
				console.log('-------- upload success --------');
				console.log(jsonData);
				console.log('field: ' + field);
			},
			/**
			 * upload fail
			 *
			 * [param] status    server api return error status, like 500
			 * [param] field
			 */
			cropUploadFail(status, field){
				console.log('-------- upload fail --------');
				console.log(status);
				console.log('field: ' + field);
			}
		}
	});
</script>

中文文档

更新日志

@1.3.0

  • 添加了俄罗斯语言包 (thanks @bigperson)
  • 添加了新属性: "headers" (用于设置请求头部:setRequestHeader)

@1.2.0

  • 兼容vue@2版本

@1.1.0

  • 调整了Props命名: "otherParams"=>"params", "langConf"=>"langExt"

示例

点我.

截图

screenshot

浏览器兼容

IE10+

配置环境

vue@1/vue@2 + webpack + es6

安装

npm

$ npm install vue-image-crop-upload

使用

Props

名称类型默认说明
fieldString'upload'向服务器上传的文件名
valueBooleantwoWay是否显示控件,双向绑定
urlString''上传接口地址
paramsObjectnull上传附带其他数据,格式"{k:v}"
headersObjectnull上传header设置,格式"{k:v}"
langTypeString'zh'语言类型,默认中文
langExtObject 语言包自行扩展
widthNumber200最终得到的图片宽度
heightNumber200最终得到的图片高度
imgFormatstring'jpg'jpg/png, 最终得到的图片格式

Events

名称说明
cropSuccess图片截取完成事件(上传前), 参数( imageDataUrl, field )
cropUploadSuccess上传成功, 参数( jsonData, field )
cropUploadFail上传失败, 参数( status, field )

自带语言包

{
    zh: {
        hint: '点击,或拖动图片至此处',
        loading: '正在上传……',
        noSupported: '浏览器不支持该功能,请使用IE10以上或其他现在浏览器!',
        success: '上传成功',
        fail: '图片上传失败',
        preview: '头像预览',
        btn: {
            off: '取消',
            close: '关闭',
            back: '上一步',
            save: '保存'
        },
        error: {
            onlyImg: '仅限图片格式',
            outOfSize: '单文件大小不能超过 ',
            lowestPx: '图片最低像素为(宽*高):'
        }
    },
    en: {
        hint: 'Click, or drag the file here',
        loading: 'Uploading……',
        noSupported: 'Browser does not support, please use IE10+ or other browsers',
        success: 'Upload success',
        fail: 'Upload failed',
        preview: 'Preview',
        btn: {
            off: 'Cancel',
            close: 'Close',
            back: 'Back',
            save: 'Save'
        },
        error: {
            onlyImg: 'Image only',
            outOfSize: 'Image exceeds size limit: ',
            lowestPx: 'The lowest pixel in the image: '
        }
    },
	ru: {
		hint: 'Нажмите, или перетащите файл в это окно',
		loading: 'Загружаю……',
		noSupported: 'Ваш браузер не поддерживается, пожалуйста, используйте IE10 + или другие браузеры',
		success: 'Загрузка выполнена успешно',
		fail: 'Ошибка загрузки',
		preview: 'Предпросмотр',
		btn: {
			off: 'Отменить',
			close: 'Закрыть',
			back: 'Назад',
			save: 'Сохранить'
		},
		error: {
			onlyImg: 'Только изображения',
			outOfSize: 'Изображение превышает предельный размер: ',
			lowestPx: 'Минимальный размер изображения: '
		}
	}
}

使用示例 vue@1

<div id="app">
	<a class="btn" @click="toggleShow">设置头像</a>
	<my-upload field="img"
		:width="300"
		:height="300"
		url="/upload"
		:params="params"
		:headers="headers"
		:value.sync="show"
		img-format="png"></my-upload>
	<img :src="imgDataUrl">
</div>

<script>
	import 'babel-polyfill'; // es6 shim
	import Vue from 'vue';
	import myUpload from 'vue-image-crop-upload';

	new Vue({
		el: '#app',
		data: {
			show: true,
			params: {
				token: '123456798',
				name: 'avatar'
			},
			headers: {
				smail: '*_~'
			},
			imgDataUrl: '' // the datebase64 url of created image
		},
		components: {
			'my-upload': myUpload
		},
		methods: {
			toggleShow() {
				this.show = !this.show;
			}
		},
		events: {
            /**
			 * crop success
			 *
			 * [param] imgDataUrl
			 * [param] field
			 */
			cropSuccess(imgDataUrl, field){
				console.log('-------- crop success --------');
				this.imgDataUrl = imgDataUrl;
			},
			/**
			 * upload success
			 *
			 * [param] jsonData   服务器返回数据,已进行json转码
			 * [param] field
			 */
			cropUploadSuccess(jsonData, field){
				console.log('-------- upload success --------');
				console.log(jsonData);
				console.log('field: ' + field);
			},
			/**
			 * upload fail
			 *
			 * [param] status    server api return error status, like 500
			 * [param] field
			 */
			cropUploadFail(status, field){
				console.log('-------- upload fail --------');
				console.log(status);
				console.log('field: ' + field);
			}
		}
	});

</script>

使用示例 vue@2

<div id="app">
	<a class="btn" @click="toggleShow">设置头像</a>
	<my-upload field="img"
        @crop-success="cropSuccess"
        @crop-upload-success="cropUploadSuccess"
        @crop-upload-fail="cropUploadFail"
        v-model="show"
		:width="300"
		:height="300"
		url="/upload"
		:params="params"
		:headers="headers"
		img-format="png"></my-upload>
	<img :src="imgDataUrl">
</div>

<script>
	import 'babel-polyfill'; // es6 shim
	import Vue from 'vue';
	import myUpload from 'vue-image-crop-upload/upload-2.vue';

	new Vue({
		el: '#app',
		data: {
			show: true,
			params: {
				token: '123456798',
				name: 'avatar'
			},
			headers: {
				smail: '*_~'
			},
			imgDataUrl: '' // the datebase64 url of created image
		},
		components: {
			'my-upload': myUpload
		},
		methods: {
			toggleShow() {
				this.show = !this.show;
			},
            /**
			 * crop success
			 *
			 * [param] imgDataUrl
			 * [param] field
			 */
			cropSuccess(imgDataUrl, field){
				console.log('-------- crop success --------');
				this.imgDataUrl = imgDataUrl;
			},
			/**
			 * upload success
			 *
			 * [param] jsonData   服务器返回数据,已进行json转码
			 * [param] field
			 */
			cropUploadSuccess(jsonData, field){
				console.log('-------- upload success --------');
				console.log(jsonData);
				console.log('field: ' + field);
			},
			/**
			 * upload fail
			 *
			 * [param] status    server api return error status, like 500
			 * [param] field
			 */
			cropUploadFail(status, field){
				console.log('-------- upload fail --------');
				console.log(status);
				console.log('field: ' + field);
			}
		}
	});

</script>
来自  https://github.com/dai-siki/vue-image-crop-upload
普通分类: