天天看點

開發執行個體:後端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實作圖檔管理功能的具體步驟。

繼續閱讀