天天看点

开发实例:后端Java和前端vue实现图片管理功能

作者:编程技术汇

实现图片管理功能需要分为前端和后端两部分。

前端:

1. 使用vue框架搭建页面,引入element-ui组件库。

2. 通过input[type=file]元素上传图片,使用element-ui的Upload组件进行封装。

3. 在上传时,可以选择是否需要剪裁、旋转和压缩图片,使用element-ui的Dialog和Slider组件进行封装。

4. 在上传完成后,将图片信息发送给后端。

后端:

1. 使用Java语言编写后端代码,使用Spring Boot框架搭建项目。

2. 使用FastDFS作为图片存储系统,将图片保存到FastDFS中。

3. 接收前端传递过来的图片信息,对图片进行剪裁、旋转和压缩操作,并保存到FastDFS中。

4. 将处理后的图片信息返回给前端。

开发实例:后端Java和前端vue实现图片管理功能

具体实现步骤如下:

前端:

1. 搭建一个基于vue框架的项目,引入element-ui组件库。

2. 创建一个上传组件,使用element-ui的Upload组件进行封装。在组件中添加一个input[type=file]元素,用于选择上传的图片。

<template>

<el-upload

class="upload-demo"

action="/upload"

:before-upload="beforeUpload"

:on-success="handleSuccess"

:on-error="handleError"

:show-file-list="false"

:headers="headers">

<el-button size="small" type="primary">点击上传</el-button>

</el-upload>

</template>

<script>

export default {

data() {

return {

headers: {

'Authorization': 'Bearer ' + localStorage.getItem('token')

}

}

},

methods: {

beforeUpload(file) {

// 在上传前进行图片剪裁、旋转和压缩操作

// 使用element-ui的Dialog和Slider组件进行封装

this.$confirm('是否需要剪裁、旋转或压缩图片?', '提示', {

confirmButtonText: '是',

cancelButtonText: '否',

type: 'warning'

}).then(() => {

this.$refs.dialog.open()

})

return false

},

handleSuccess(res) {

// 图片上传成功后的处理逻辑

},

handleError(err) {

// 图片上传失败后的处理逻辑

}

}

}

</script>

           

3. 创建一个Dialog组件,用于选择是否需要对图片进行剪裁、旋转和压缩操作。使用element-ui的Dialog和Slider组件进行封装。

<template>

<div>

<el-dialog

title="图片处理"

:visible.sync="dialogVisible"

width="30%">

<el-form :model="form" label-position="left" label-width="80px">

<el-form-item label="剪裁">

<el-switch v-model="form.crop"></el-switch>

</el-form-item>

<el-form-item label="旋转">

<el-slider v-model="form.rotate" :min="-180" :max="180" show-input></el-slider>

</el-form-item>

<el-form-item label="压缩">

<el-slider v-model="form.compress" :min="0" :max="100" show-input></el-slider>

</el-form-item>

</el-form>

<div slot="footer" class="dialog-footer">

<el-button @click="dialogVisible = false">取消</el-button>

<el-button type="primary" @click="handleConfirm">确定</el-button>

</div>

</el-dialog>

</div>

</template>

<script>

export default {

data() {

return {

dialogVisible: false,

form: {

crop: false,

rotate: 0,

compress: 0

}

}

},

methods: {

open() {

this.dialogVisible = true

},

handleConfirm() {

// 确认后,将选择的处理方式传递给父组件进行处理

this.$emit('handle-process', this.form)

this.dialogVisible = false

}

}

}

</script>

           

4. 在上传组件中添加一个Dialog组件,用于选择是否需要对图片进行剪裁、旋转和压缩操作。并在beforeUpload事件中调用Dialog组件。

<template>

<el-upload

class="upload-demo"

action="/upload"

:before-upload="beforeUpload"

:on-success="handleSuccess"

:on-error="handleError"

:show-file-list="false"

:headers="headers">

<el-button size="small" type="primary">点击上传</el-button>

<process-dialog ref="dialog" @handle-process="handleProcess"></process-dialog>

</el-upload>

</template>

<script>

import ProcessDialog from './ProcessDialog.vue'

export default {

components: {

ProcessDialog

},

data() {

return {

headers: {

'Authorization': 'Bearer ' + localStorage.getItem('token')

}

}

},

methods: {

beforeUpload(file) {

// 在上传前进行图片剪裁、旋转和压缩操作

this.$refs.dialog.open()

return false

},

handleProcess(form) {

// 处理图片

const file = this.$refs.upload.uploadFiles[0].raw

const reader = new FileReader()

reader.onload = (e) => {

const img = new Image()

img.src = e.target.result

img.onload = () => {

const canvas = document.createElement('canvas')

const ctx = canvas.getContext('2d')

let width = img.width

let height = img.height

if (form.crop) {

// 进行图片剪裁

const cropWidth = Math.min(width, height)

const cropHeight = Math.min(width, height)

const cropX = (width - cropWidth) / 2

const cropY = (height - cropHeight) / 2

canvas.width = cropWidth

canvas.height = cropHeight

ctx.drawImage(img, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight)

width = cropWidth

height = cropHeight

img.src = canvas.toDataURL('image/jpeg', 1)

}

if (form.rotate !== 0) {

// 进行图片旋转

const rotate = form.rotate * Math.PI / 180

canvas.width = height

canvas.height = width

ctx.translate(height / 2, width / 2)

ctx.rotate(rotate)

ctx.drawImage(img, -width / 2, -height / 2, width, height)

width = canvas.width

height = canvas.height

img.src = canvas.toDataURL('image/jpeg', 1)

}

if (form.compress !== 0) {

// 进行图片压缩

const quality = form.compress / 100

canvas.width = width

canvas.height = height

ctx.drawImage(img, 0, 0, width, height)

img.src = canvas.toDataURL('image/jpeg', quality)

}

this.uploadFile(img.src)

}

}

reader.readAsDataURL(file)

},

uploadFile(base64) {

// 将处理后的图片上传到服务器

const formData = new FormData()

const blob = this.base64ToBlob(base64)

formData.append('file', blob, 'test.jpg')

axios.post('/upload', formData, {

headers: {

'Content-Type': 'multipart/form-data',

'Authorization': 'Bearer ' + localStorage.getItem('token')

}

}).then(res => {

console.log(res.data)

})

},

base64ToBlob(dataURL) {

const arr = dataURL.split(',')

const mime = arr[0].match(/:(.*?);/)[1]

const bstr = atob(arr[1])

let n = bstr.length

const u8arr = new Uint8Array(n)

while (n--) {

u8arr[n] = bstr.charCodeAt(n)

}

return new Blob([u8arr], { type: mime })

},

handleSuccess(res) {

// 图片上传成功后的处理逻辑

},

handleError(err) {

// 图片上传失败后的处理逻辑

}

}

}

</script>           

后端:

1. 在Spring Boot项目中添加FastDFS依赖。

<dependency>

<groupId>com.github.tobato</groupId>

<artifactId>fastdfs-client</artifactId>

<version>1.27.2</version>

</dependency>           

2. 创建一个上传接口,接收前端上传的图片,并将图片保存到FastDFS中。

@RestController

public class UploadController {

@Autowired

private FastFileStorageClient fastFileStorageClient;

@PostMapping("/upload")

public String upload(@RequestParam("file") MultipartFile file) throws IOException, MyException {

byte[] bytes = file.getBytes();

String originalFilename = file.getOriginalFilename();

String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

StorePath storePath = fastFileStorageClient.uploadFile(bytes, extName);

return storePath.getFullPath();

}

}           

3. 创建一个处理图片的接口,接收前端传递过来的图片信息,对图片进行剪裁、旋转和压缩操作,并保存到FastDFS中。

@RestController

public class ImageController {

@Autowired

private FastFileStorageClient fastFileStorageClient;

@PostMapping("/image/process")

public String processImage(@RequestBody ProcessRequest request) throws IOException, MyException {

byte[] bytes = Base64.getDecoder().decode(request.getBase64());

String originalFilename = request.getFilename();

String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

StorePath storePath = fastFileStorageClient.uploadFile(bytes, extName);

return storePath.getFullPath();

}

}           

4. 创建一个ProcessRequest类,用于接收前端传递过来的图片信息。

public class ProcessRequest {

private String filename;

private String base64;

public String getFilename() {

return filename;

}

public void setFilename(String filename) {

this.filename = filename;

}

public String getBase64() {

return base64;

}

public void setBase64(String base64) {

this.base64 = base64;

}

}           

以上就是使用Java和vue实现图片管理功能的具体步骤。

继续阅读