使用阿里云的oss对象存储服务实现图片上传(前端vue后端java详解)
前端Vue代码示例:
<template>
<div>
<input type="file" @change="uploadImage" />
</div>
</template>
<script>
export default {
methods: {
uploadImage(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
// 使用axios发送请求到后端Java服务
axios.post('/upload/image', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
// 处理响应,例如获取返回的图片URL
console.log(response.data.url);
})
.catch(error => {
console.error(error);
});
}
}
};
</script>
后端Java代码示例(使用Spring Boot):
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.StringUtils;
@RestController
public class UploadController {
private static String endpoint = "您的阿里云OSS端点";
private static String accessKeyId = "您的阿里云AccessKeyId";
private static String accessKeySecret = "您的阿里云AccessKeySecret";
private static String bucketName = "您的OSS桶名";
@PostMapping("/upload/image")
public String uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "文件不能为空";
}
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
String fileName = file.getOriginalFilename();
// 生成文件路径和文件名
String objectName = "uploads/" + fileName;
// 上传文件
ossClient.putObject(bucketName, objectName, file.getInputStream());
// 返回文件的URL
String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
return "{\"url\": \"" + url + "\"}";
} catch (Exception e) {
e.printStackTrace();
评论已关闭