好文推荐
今日推荐《Spring AI 再更新:如何借助全局参数实现智能数据库操作与个性化待办管理》 这篇文章介绍了基于 Spring AI 的系统优化,不仅为我们提供了一个强大的智能助手框架,也为实际业务中的智能化系统提供了可借鉴的方案,可以基于此进一步扩展功能,打造更加智能化和个性化的业务解决方案。
在现代Web应用中,文件上传、下载和删除功能是非常常见的需求。本文将介绍如何使用Spring Boot作为后端框架,Vue.js作为前端框架,实现本地文件的上传、下载和删除功能。
首先,创建一个新的Spring Boot项目,并添加必要的依赖项,如Spring Web和Spring Boot DevTools。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
创建一个Controller类来处理文件的上传、下载和删除请求。
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/api/files")
public class FileController {
private final Path rootLocation = Paths.get("uploads");
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
return ResponseEntity.ok().body("File uploaded successfully: " + file.getOriginalFilename());
} catch (Exception e) {
return ResponseEntity.status(500).body("Could not upload the file: " + file.getOriginalFilename() + "!");
}
}
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
try {
Path file = rootLocation.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
} catch (MalformedURLException e) {
return ResponseEntity.badRequest().build();
}
}
@DeleteMapping("/delete/{filename:.+}")
public ResponseEntity<String> deleteFile(@PathVariable String filename) {
try {
Files.delete(rootLocation.resolve(filename));
return ResponseEntity.ok().body("File deleted successfully: " + filename);
} catch (Exception e) {
return ResponseEntity.status(500).body("Could not delete the file: " + filename + "!");
}
}
}
在application.properties
文件中配置文件存储路径:
file.upload-dir=uploads
使用Vue CLI创建一个新的Vue项目,并安装必要的依赖项,如axios用于HTTP请求。
vue create file-upload-download-delete
cd file-upload-download-delete
npm install axios
创建一个Vue组件来处理文件的上传、下载和删除操作。
<template>
<div>
<h2>File Upload</h2>
<input type="file" @change="handleFileUpload" />
<button @click="uploadFile">Upload</button>
<h2>File Download</h2>
<input type="text" v-model="fileName" placeholder="Enter file name" />
<button @click="downloadFile">Download</button>
<h2>File Delete</h2>
<input type="text" v-model="deleteFileName" placeholder="Enter file name" />
<button @click="deleteFile">Delete</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
fileName: '',
deleteFileName: ''
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
},
async uploadFile() {
const formData = new FormData();
formData.append('file', this.file);
try {
const response = await axios.post('/api/files/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
alert(response.data);
} catch (error) {
alert(error.response.data);
}
},
async downloadFile() {
try {
const response = await axios.get(`/api/files/download/${this.fileName}`, {
responseType: 'blob'
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', this.fileName);
document.body.appendChild(link);
link.click();
} catch (error) {
alert(error.response.data);
}
},
async deleteFile() {
try {
const response = await axios.delete(`/api/files/delete/${this.deleteFileName}`);
alert(response.data);
} catch (error) {
alert(error.response.data);
}
}
}
};
</script>
配置Vue Router以便访问该组件。
import Vue from 'vue';
import Router from 'vue-router';
import FileComponent from './components/FileComponent.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'FileComponent',
component: FileComponent
}
]
});
通过本文,我们学习了如何使用Spring Boot和Vue.js实现本地文件的上传、下载和删除功能。后端使用Spring Boot处理文件的存储和操作,前端使用Vue.js提供用户界面和交互。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。