一、input上传
- 前端页面
<template>
<div>
<li>
<h3>添加新图:</h3>
<input type="text" v-model="name" />
<br />
<br />
<input
type="file"
id="saveImage"
name="photo"
accept="image/png, image/gif, image/jpeg"
ref="new_image"
/>
<br />
<br />
<el-button @click="addImage">确认添加</el-button>
</li>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return { name: "" };
},
components: {},
methods: {
addImage: function() {
let self = this;
if (self.$refs.new_image.files.length !== 0) {
let formData = new FormData();
// 文本框数据
formData.append("name", this.name);
// 通过append向form对象添加数据
formData.append("image_data", self.$refs.new_image.files[0]);
//单个文件进行上传
axios
.post("http://localhost:8888/upload", formData, {
"Content-Type": "multipart/form-data"
})
.then(response => {
console.log(response.data);
});
}
}
}
};
</script>
界面:
- 后端控制器
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
@PostMapping
public Map<String, Object> upload(@RequestParam(name = "image_data")
MultipartFile file,
@RequestParam(name = "name") String name) {
Map<String, Object> map = new HashMap<>();
// 文件上传
if (!file.isEmpty()) {
try {
Resource resource = new ClassPathResource("/");
String path = resource.getFile().getPath();
// 获取resources路径,并获取文件名
String newCompanyImagepath = path+"/" + file.getOriginalFilename();
// 创建文件对象
File newFile = new File(newCompanyImagepath);
if (!newFile.exists()) {
newFile.createNewFile();
}
System.out.println(name);
System.out.println(newFile.getAbsoluteFile());
// 获取输出流
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(newFile));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
map.put("msg", "图片上传失败");
return map;
} catch (IOException e) {
e.printStackTrace();
map.put("msg", "图片上传失败");
return map;
}
}
map.put("msg", "上传成功");
return map;
}
}
二、 element ui--Upload 组件上传
- 前端页面
<template>
<el-upload
class="avatar-uploader"
action="http://localhost:8888/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<!-- 显示图片 -->
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>
<script>
export default {
data() {
return { imageUrl: "" };
},
components: {},
methods: {
// 头像处理
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
// 文件大小
const isLt2M = file.size / 1024 / 1024 < 2;
// 文件判断
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG 格式!");
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return isJPG && isLt2M;
}
}
};
</script>
- 后端 控制器
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
@PostMapping
public Map<String, Object> upload(MultipartFile file) {
Map<String, Object> map = new HashMap<>();
// 文件上传
if (!file.isEmpty()) {
try {
Resource resource = new ClassPathResource("/");
String path = resource.getFile().getPath();
// 获取resources路径,并获取文件名
String newCompanyImagepath = path+"/" + file.getOriginalFilename();
// 创建文件对象
File newFile = new File(newCompanyImagepath);
if (!newFile.exists()) {
newFile.createNewFile();
}
System.out.println(newFile.getAbsoluteFile());
// 获取输出流
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(newFile));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
map.put("msg", "图片上传失败");
return map;
} catch (IOException e) {
e.printStackTrace();
map.put("msg", "图片上传失败");
return map;
}
}
map.put("msg", "上传成功");
return map;
}
}
二、 上传示例
- 前端代码
<template>
<!-- 图片上传 -->
<div>
<el-upload
ref="upload"
action="http://localhost:8888/goodsPic"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-success="handlePictureSuccess"
:on-remove="handleRemove"
>
<i class="el-icon-plus"></i>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
images: []
};
},
methods: {
handlePictureSuccess(response, file) {
// 图片内容
// console.log( URL.createObjectURL(file.raw));
// 向数组添加图片
this.images.push(response.msg);
console.log(response.msg);
},
// 移除图片
handleRemove(file, fileList) {
// 删除数据
this.images.forEach((item, index) => {
if (file.response.msg == item) {
this.images.splice(index, 1);
}
});
console.log(this.images);
console.log(file.response.msg);
console.log(file, fileList);
},
// 浏览图片
handlePictureCardPreview(file) {
console.log(file);
}
}
};
</script>
- 后端控制器
配置路径:
# 文件上传路径
upload.path=images
控制器:
@RestController
@RequestMapping(value = "/goodsPic", produces = {"application/json;charset=UTF-8"})
@CrossOrigin
@Slf4j
public class GoodsPicController {
@Value("${upload.path}")
private String uploadFolder;
@Autowired
private GoodsPicService goodsPicService;
/**
* MultipartFile:SpringMVC的multipartFile对象,用于接收前端请求传入的FormData。
* @param file
* @return
*/
@PostMapping
public Result upload(MultipartFile file) {
if (Objects.isNull(file) || file.isEmpty()) {
log.error("文件为空");
return Result.ok("件为空,请重新上传");
}
try {
byte[] bytes = file.getBytes();
// 获取类路径
Resource resource=new ClassPathResource("/");
String strPath=resource.getFile().getPath();
// 定义一个上传路径
String fileName=file.getOriginalFilename();
fileName=UUID.randomUUID().toString().replace("-","")
+fileName.substring(fileName.indexOf("."),fileName.length());
Path path= Paths.get(strPath+"/"+uploadFolder+"/"+fileName);
// 如果没有files文件夹,则创建
if (!Files.isWritable(path)) {
Files.createDirectories(Paths.get(strPath+"/"+uploadFolder));
}
//文件写入指定路径
Files.write(path, bytes);
return Result.ok(fileName);
} catch (IOException e) {
return Result.ok("上传失败"+e.getMessage());
}
}
}
-
上传测试