webapi+vue3实现前后端图片传输
2.前端代码
<template><div class="Thisform"><el-form ref="form" :model="form" label-width="80px"><el-form-item label="咖啡图片:"><input type="file" @change="getFile" /></el-form-item><el-form-item style="padding-left:50px"><el-button type="primary" @click="onSubmit">立即添加</el-button><el-button @click="toSelectCoffee">取消</el-button></el-form-item></el-form><div v-if="imageUrl" class="image-preview"><p>上传成功!</p><img :src="imageUrl" alt="上传的图片" width="200" /></div></div></template><script setup>
import { ref } from 'vue';
import axios from 'axios';
const file = ref(null);
const imageUrl = ref('');
const onSubmit = async (event) => {event.preventDefault(); if (!file.value) {console.log("没有选择文件");return;}const param = new FormData();param.append("file", file.value);try {const response = await axios.post('http://localhost:19001/api/dangerouspackboxinfo/getimage', param, {headers: {"Content-Type": "multipart/form-data"}});console.log(response.data.data);imageUrl.value = `http://localhost:19001${response.data.data}`; console.log("上传成功后的图片 URL:", imageUrl.value);} catch (error) {console.error('上传失败:', error);}
};
const getFile = (event) => {file.value = event.target.files[0];console.log(file.value);
};
const toSelectCoffee = () => {console.log("取消操作");
};
</script><style scoped>.Thisform {width: 30%;padding-left: 500px;padding-top: 50px;}</style>
3.后端接口
[HttpPost("GetImage")]public async Task<string> GetImage(IFormFile file){if (file == null || file.Length == 0){return "没有上传文件.";}var uploadPath = Path.Combine(_hostingEnvironment.ContentRootPath, "wwwroot", "File/images");if (!Directory.Exists(uploadPath)){Directory.CreateDirectory(uploadPath);}var fileExtension = Path.GetExtension(file.FileName);var datetime = GetTimeStamp();var fileName = $"{datetime}{fileExtension}"; var filePath = Path.Combine(uploadPath, fileName);using (var fileStream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(fileStream);}var fileUrl = "/File/images/" + fileName;return fileUrl; }private string GetTimeStamp(){TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);return Convert.ToInt64(ts.TotalMilliseconds).ToString();}
辅助类
public static class StreamHelp{public static void StreamToFile(Stream stream, string fileName){byte[] bytes = new byte[stream.Length];stream.Read(bytes, 0, bytes.Length);stream.Seek(0, SeekOrigin.Begin);FileStream fs = new FileStream(fileName, FileMode.Create);BinaryWriter bw = new BinaryWriter(fs);bw.Write(bytes);bw.Close();fs.Close();}public static Stream FileToStream(string fileName){FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);byte[] bytes = new byte[fileStream.Length];fileStream.Read(bytes, 0, bytes.Length);fileStream.Close();Stream stream = new MemoryStream(bytes);return stream;}public static byte[] StreamToBytes(Stream stream){byte[] bytes = new byte[stream.Length];stream.Read(bytes, 0, bytes.Length);stream.Seek(0, SeekOrigin.Begin);return bytes;}public static Stream BytesToStream(byte[] bytes){Stream stream = new MemoryStream(bytes);return stream;}}