用vue和java写一个文件上传并解析文件内容的代码
时间: 2024-05-27 12:14:08 浏览: 211
上传文件的java代码
前端代码:
<template>
<div>
<input type="file" @change="handleUpload" ref="fileInput" />
<button @click="handleSubmit">上传</button>
<div v-if="showContent">
<h3>文件内容</h3>
<pre>{{ fileContent }}</pre>
</div>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
fileContent: null,
showContent: false,
};
},
methods: {
handleUpload(event) {
this.file = event.target.files[0];
},
async handleSubmit() {
const formData = new FormData();
formData.append("file", this.file);
try {
const response = await fetch("/api/upload", {
method: "POST",
body: formData,
});
const data = await response.json();
this.fileContent = data.content;
this.showContent = true;
} catch (error) {
console.error(error);
}
},
},
};
</script>
后端代码:
@RestController
@RequestMapping("/api")
public class FileUploadController {
@PostMapping("/upload")
public Map<String, String> uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
InputStream inputStream = file.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
inputStream.close();
Map<String, String> result = new HashMap<>();
result.put("content", sb.toString());
return result;
}
}
阅读全文