elementui上传text文件到java后端,前端的代码和后端的完整代码怎么写?
时间: 2023-05-29 12:01:12 浏览: 238
java学习笔记.txt
前端代码:
```
<template>
<el-upload
class="upload-demo"
ref="upload"
:action="uploadUrl"
:on-change="handleChange"
:auto-upload="false"
:file-list="fileList"
:headers="headers"
>
<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
<el-button
style="margin-left: 10px;"
size="small"
type="success"
@click="handleUpload"
:disabled="fileList.length === 0"
>
上传到服务器
</el-button>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: [], // 文件列表
uploadUrl: '', // 后端接口地址
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'), // 请求头中的 token
},
};
},
methods: {
// 选择文件时触发
handleChange(file) {
this.fileList.push(file.raw);
},
// 点击上传按钮时触发
handleUpload() {
let formData = new FormData();
this.fileList.forEach((file) => {
formData.append('file', file);
});
this.$refs.upload.submit(formData);
},
},
};
</script>
```
后端代码(使用Spring Boot框架):
```
@RestController
@RequestMapping("/api")
public class FileController {
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
}
String fileName = file.getOriginalFilename();
byte[] bytes;
try {
bytes = file.getBytes();
} catch (IOException e) {
return new ResponseEntity<>("Failed to read file", HttpStatus.INTERNAL_SERVER_ERROR);
}
// save the file
try {
File newFile = new File(fileName);
OutputStream os = new FileOutputStream(newFile);
os.write(bytes);
os.close();
} catch (IOException e) {
return new ResponseEntity<>("Failed to save file", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}
}
```
以上代码仅供参考,实际应用中需要根据具体情况进行适当修改。
阅读全文