文件上传下载前后端代码
时间: 2023-12-20 16:30:39 浏览: 64
上传文件后台代码
4星 · 用户满意度95%
以下是文件上传下载前后端代码的示例:
前端代码:
文件上传:
```javascript
<template>
<div>
<input type="file" ref="file" @change="uploadFile"/>
</div>
</template>
<script>
export default {
methods: {
uploadFile() {
let file = this.$refs.file.files[0];
let formData = new FormData();
formData.append('file', file);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
});
}
}
}
</script>
```
文件下载:
```javascript
<template>
<div>
<button @click="downloadFile">下载文件</button>
</div>
</template>
<script>
export default {
methods: {
downloadFile() {
axios({
url: '/download',
method: 'get',
responseType: 'blob'
}).then(res => {
let blob = new Blob([res.data]);
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = 'file.txt';
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
}).catch(err => {
console.log(err);
});
}
}
}
</script>
```
后端代码:
文件上传:
```java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
```
文件下载:
```java
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
String filePath = "D:/upload/";
String fileName = "file.txt";
File file = new File(filePath + fileName);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
```
阅读全文