当前位置: 首页 > wzjs >正文

2015做那些网站致富小程序开发哪家好

2015做那些网站致富,小程序开发哪家好,xampp配置多网站,单页网站模板做seo前言 在实际生产环境中,我们通常会将图片等静态资源存储在云端对象存储服务(如阿里云OSS、七牛云、腾讯云COS等)上。本文将介绍如何改造之前的本地存储方案,实现基于云端存储的图片上传与回显功能。 一、技术选型 云存储服务&a…

前言

在实际生产环境中,我们通常会将图片等静态资源存储在云端对象存储服务(如阿里云OSS、七牛云、腾讯云COS等)上。本文将介绍如何改造之前的本地存储方案,实现基于云端存储的图片上传与回显功能。

一、技术选型

  • 云存储服务:阿里云OSS(其他云服务类似)
  • 后端:SpringBoot 2.x + OSS SDK
  • 前端:Vue 2.x + Element UI

二、阿里云OSS准备

  1. 开通OSS服务
  2. 创建Bucket(存储空间)
  3. 获取AccessKey(访问密钥)

三、后端改造

1. 添加OSS依赖

<!-- 阿里云OSS -->
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version>
</dependency>

2. 配置OSS参数

application.properties中:

# 阿里云OSS配置
aliyun.oss.endpoint=your-oss-endpoint
aliyun.oss.accessKeyId=your-access-key-id
aliyun.oss.accessKeySecret=your-access-key-secret
aliyun.oss.bucketName=your-bucket-name
aliyun.oss.urlPrefix=https://your-bucket-name.oss-cn-hangzhou.aliyuncs.com/

3. 创建OSS配置类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class OssConfig {@Value("${aliyun.oss.endpoint}")private String endpoint;@Value("${aliyun.oss.accessKeyId}")private String accessKeyId;@Value("${aliyun.oss.accessKeySecret}")private String accessKeySecret;@Beanpublic OSS ossClient() {return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);}
}

4. 创建OSS上传工具类

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.util.UUID;@Component
public class OssUploadUtil {@Autowiredprivate OSS ossClient;@Value("${aliyun.oss.bucketName}")private String bucketName;@Value("${aliyun.oss.urlPrefix}")private String urlPrefix;public String upload(MultipartFile file) throws IOException {// 生成唯一文件名String originalFilename = file.getOriginalFilename();String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));String newFileName = "images/" + UUID.randomUUID().toString() + fileExt;// 上传到OSSossClient.putObject(new PutObjectRequest(bucketName, newFileName, file.getInputStream()));// 返回完整的访问URLreturn urlPrefix + newFileName;}
}

5. 修改控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/api/image")
public class ImageController {@Autowiredprivate OssUploadUtil ossUploadUtil;@PostMapping("/upload")public String uploadImage(@RequestParam("file") MultipartFile file) {if (file.isEmpty()) {return "请选择文件";}try {String imageUrl = ossUploadUtil.upload(file);return imageUrl; // 直接返回完整的图片URL} catch (IOException e) {e.printStackTrace();return "上传失败";}}
}

四、前端改造

前端几乎不需要修改,因为OSS上传后返回的是可以直接访问的URL,比本地存储更简单。

1. 修改上传成功处理

handleUploadSuccess(response, file) {if (response && response.startsWith('http')) {this.imageUrl = response; // 直接使用返回的完整URLthis.$message.success('上传成功');} else {this.$message.error('上传失败');}
}

2. 移除静态资源代理配置

因为图片URL已经是完整的HTTP地址,不再需要代理:

module.exports = {devServer: {proxy: {'/api': {target: 'http://localhost:8080', // 后端地址changeOrigin: true,pathRewrite: {'^/api': ''}}// 移除/images的代理配置}}
};

五、安全增强

1. 后端签名直传(推荐)

更安全的做法是前端从后端获取签名,然后直接上传到OSS,不经过后端服务器:

后端添加签名接口
@GetMapping("/oss/policy")
public Map<String, String> getOssPolicy() {// 设置上传策略long expireTime = 30;long expireEndTime = System.currentTimeMillis() + expireTime * 1000;Date expiration = new Date(expireEndTime);// 设置文件路径和大小限制String dir = "images/";long maxSize = 10 * 1024 * 1024; // 10MB// 生成策略PolicyConditions policyConds = new PolicyConditions();policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);policyConds.addConditionItem(PolicyConditions.COND_KEY, PolicyConditions.COND_STARTS_WITH, dir);// 生成签名String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);String encodedPolicy = BinaryUtil.toBase64String(binaryData);String postSignature = ossClient.calculatePostSignature(postPolicy);// 返回给前端Map<String, String> respMap = new HashMap<>();respMap.put("accessid", accessKeyId);respMap.put("policy", encodedPolicy);respMap.put("signature", postSignature);respMap.put("dir", dir);respMap.put("host", urlPrefix);respMap.put("expire", String.valueOf(expireEndTime / 1000));return respMap;
}
前端改造
<template><el-uploadclass="upload-demo":action="ossUploadUrl":data="ossData":before-upload="beforeUpload":on-success="handleUploadSuccess"><!-- 上传按钮 --></el-upload>
</template><script>
export default {data() {return {ossUploadUrl: '', // OSS上传地址ossData: {}      // OSS上传参数};},methods: {async getOssPolicy() {const res = await this.$axios.get('/api/image/oss/policy');this.ossUploadUrl = res.data.host;this.ossData = {key: res.data.dir + '${filename}', // OSS文件路径policy: res.data.policy,OSSAccessKeyId: res.data.accessid,signature: res.data.signature,success_action_status: '200' // 成功返回状态码};},beforeUpload(file) {// 每次上传前获取新的签名return this.getOssPolicy().then(() => {const isImage = /\.(jpg|jpeg|png|gif)$/i.test(file.name);const isLt10M = file.size / 1024 / 1024 < 10;if (!isImage) {this.$message.error('只能上传图片文件!');}if (!isLt10M) {this.$message.error('图片大小不能超过10MB!');}return isImage && isLt10M;});},handleUploadSuccess(res, file) {// 拼接完整URLthis.imageUrl = this.ossUploadUrl + '/' + file.name;this.$message.success('上传成功');}}
};
</script>

六、总结

云端存储相比本地存储有以下优势:

  1. 高可用性:云服务提供99.9%以上的可用性
  2. 高扩展性:存储空间可无限扩展
  3. 高性能:CDN加速全球访问
  4. 低成本:按量付费,无需自建存储服务器
  5. 安全性:提供多种安全防护机制

本文详细介绍了基于阿里云OSS的图片上传方案,其他云存储服务实现方式类似。签名直传方案既能保证安全性,又能减轻服务器压力,是生产环境推荐的做法。

最重要的啊,也是本人和朋友写代码发现的
就是controller类里面的那个@RequestParam("file")
这个file ,之前我们用的是image 因为这个一个词,改了不下10词代码,最后也是突然醒悟。
下面是正确的方法,可以按照之前的步骤来,大概是不会错了。

 @PostMapping("/upload")public String uploadImage(@RequestParam("file") MultipartFile file) {if (file.isEmpty()) {return "请选择文件";}try {String imageUrl = ossUploadUtil.upload(file);return imageUrl; // 直接返回完整的图片URL} catch (IOException e) {e.printStackTrace();return "上传失败";}}
}

希望这篇文章对大家有帮助!

http://www.dtcms.com/wzjs/497170.html

相关文章:

  • 网站建设技术架构和语言博客网站
  • 能免费做婚礼邀请函的网站网店代运营诈骗
  • 网站设计书小程序开发流程
  • 日本人做网站如何搭建公司网站
  • 做网络销售都做什么网站seo是哪个英文的缩写
  • 网站建设好评语百度指数查询排行榜
  • 网站建设 案例北京百度搜索优化
  • 什么网站可以自己做房子设计图万能导航网
  • 郑州汉狮做网站多少钱冯耀宗seo视频教程
  • 河北省建设监理协会网站大数据智能营销系统
  • 网站忧化教程seo薪酬水平
  • 用php做网站用到的工具免费站推广网站不用下载
  • 哪些网站是做货源的重庆网站设计
  • 深圳平湖网站开发网页设计成品源代码
  • 沈阳视频制作公司某网站seo策划方案
  • 什么时候能用ipv6做网站网络营销能干什么工作
  • 湖南省建设厅易小林百度seo价格
  • 做网站赌博彩票算犯法吗重庆网站搭建
  • 用DW做的网站生成链接最新清远发布
  • seo教程技术淘宝seo是什么意思啊
  • 深圳微商城网站制作费用百度账号中心官网
  • 佛山建网站常熟seo网站优化软件
  • 涟源网站建设网站维护的主要内容
  • 咸阳免费做网站公司网址检测
  • 中核工建设集团OA网站企业营销案例
  • 互助县wap网站建设公司cpc广告点击日结联盟
  • 如何利用网站新闻做推广数据分析师就业前景
  • 北京网站制作公司报价seo快速排名优化
  • 通用网站建设需求分析阳西网站seo
  • jz做网站三亚百度推广开户