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

湖南建设网站官网今日新闻 最新消息 大事

湖南建设网站官网,今日新闻 最新消息 大事,做网站开发要学什么软件,兼职做任务的网站SpringBoot整合阿里云OSS文件上传、下载、查看、删除1、开发准备1.1 前置知识1.2 环境参数1.3 你能学到什么2. 使用阿里云OSS2.1 创建Bucket2.2 管理文件2.3 阿里云OSS文档3. 项目初始化3.1 创建SpringBoot项目3.2 Maven依赖3.3 安装lombok插件4. 后端服务编写4.1 阿里云OSS配置…

SpringBoot整合阿里云OSS文件上传、下载、查看、删除

  • 1、开发准备
    • 1.1 前置知识
    • 1.2 环境参数
    • 1.3 你能学到什么
  • 2. 使用阿里云OSS
    • 2.1 创建Bucket
    • 2.2 管理文件
    • 2.3 阿里云OSS文档
  • 3. 项目初始化
    • 3.1 创建SpringBoot项目
    • 3.2 Maven依赖
    • 3.3 安装lombok插件
  • 4. 后端服务编写
    • 4.1 阿里云OSS配置
    • 4.2 后端业务
      • 4.2.1 vo
      • 4.2.2 service
      • 4.2.3 controller
  • 5. 前端页面编写与测试
    • 5.1 文件上传页面
    • 5.2 文件管理页面

1、开发准备

1.1 前置知识

java基础以及SpringBoot简单基础知识即可。

1.2 环境参数

  • 开发工具:IDEA
  • 基础环境:Maven+JDK8
  • 所用技术:SpringBoot、lombok、阿里云OSS存储服务
  • SpringBoot版本:2.1.4

1.3 你能学到什么

  • OSS简介,以及阿里云OSS控制台快速入门使用
  • SpringBoot 整合 阿里云OSS 存储服务,进行文件上传、下载、查看、删除
  • 阿里云OSS文档介绍,以及快速入门使用
  • lombak入门使用以及IDEA lombak插件安装
  • SpringMVC与AJAX前后端分离交互
  • AJAX文件异步上传

2. 使用阿里云OSS

对象存储OSS的多重冗余架构设计,为数据持久存储提供可靠保障。

2.1 创建Bucket

使用OSS,首先需要创建Bucket,Bucket翻译成中文是水桶的意思,把存储的图片资源看做是水,想要盛水必须得
有桶。
进入控制台,https://oss.console.aliyun.com/overview
在这里插入图片描述
在这里插入图片描述
创建完成后,在左侧可以看到已经创建好的Bucket:
在这里插入图片描述
选择Bucket后,即可看到对应的信息,如:url、消耗流量等
在这里插入图片描述

2.2 管理文件

可以通过在线的方式进行管理文件
在这里插入图片描述

2.3 阿里云OSS文档

阿里云OSS文档
在这里插入图片描述
右侧的开发指南说的更加详细
在这里插入图片描述
阿里云虽然提供了完整的文档,但是做一个完整的前后端交互的文件上传、下载、查看、删除等操作,对于小白来说还是有点难度的,所以我把自己学习OSS的步骤以及代码分享了出来,共有需要的人使用。

3. 项目初始化

3.1 创建SpringBoot项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.2 Maven依赖

<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.4</version><scope>provided</scope></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.9.9</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.8.1</version></dependency>

3.3 安装lombok插件

因为项目中使用了lombok的@Data注解,当然你也可以自己写get、set等方法。
File——>settings——>Plugins
在这里插入图片描述
在这里插入图片描述
然后restart IDEA即可。

4. 后端服务编写

在这里插入图片描述

4.1 阿里云OSS配置

在resource下新建一个application-oss.properties

aliyun.endpoint=oss-cn-shanghai.aliyuncs.com
aliyun.accessKeyId=你的accessKeyId
aliyun.accessKeySecret=你的accessKeySecret
aliyun.bucketName=gaojun-testbucket
aliyun.urlPrefix=http://gaojun-testbucket.oss-cn-shanghai.aliyuncs.com/

在这里插入图片描述
在这里插入图片描述
在java的包下新建一个config包,创建一个AliyunConfig.java

package com.example.ossdemo.config;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/*** @desc** @author gaojun* @email 15037584397@163.com*/
@Configuration
@PropertySource(value = {"classpath:application-oss.properties"})
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunConfig {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;private String urlPrefix;@Beanpublic OSS oSSClient() {return new OSSClient(endpoint, accessKeyId, accessKeySecret);}
}

4.2 后端业务

4.2.1 vo

package com.example.ossdemo.vo;
import lombok.Data;
/*** @author gaojun* @desc 用于前后端交互的返回值* @email 15037584397@163.com*/
@Data
public class FileUploadResult {// 文件唯一标识private String uid;// 文件名private String name;// 状态有:uploading done error removedprivate String status;// 服务端响应内容,如:'{"status": "success"}'private String response;
}

4.2.2 service

package com.example.ossdemo.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.example.ossdemo.config.AliyunConfig;
import com.example.ossdemo.vo.FileUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;
/*** @author gaojun* @desc* @email 15037584397@163.com*/
@Service
public class FileUploadService {// 允许上传的格式private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png"};@Autowiredprivate OSS ossClient;@Autowiredprivate AliyunConfig aliyunConfig;/*** @author gaojun* @desc 文件上传*  文档链接 https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.749.11987a7dRYVSzn* @email 15037584397@163.com*/public FileUploadResult upload(MultipartFile uploadFile) {// 校验图片格式boolean isLegal = false;for (String type : IMAGE_TYPE) {if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)) {isLegal = true;break;}}//封装Result对象,并且将文件的byte数组放置到result对象中FileUploadResult fileUploadResult = new FileUploadResult();if (!isLegal) {fileUploadResult.setStatus("error");return fileUploadResult;}//文件新路径String fileName = uploadFile.getOriginalFilename();String filePath = getFilePath(fileName);// 上传到阿里云try {ossClient.putObject(aliyunConfig.getBucketName(), filePath, newByteArrayInputStream(uploadFile.getBytes()));} catch (Exception e) {e.printStackTrace();//上传失败fileUploadResult.setStatus("error");return fileUploadResult;}fileUploadResult.setStatus("done");fileUploadResult.setResponse("success");//this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保持数据库fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));return fileUploadResult;}/*** @author gaojun* @desc 生成路径以及文件名 例如://images/2019/04/28/15564277465972939.jpg* @email 15037584397@163.com*/private String getFilePath(String sourceFileName) {DateTime dateTime = new DateTime();return "images/" + dateTime.toString("yyyy")+ "/" + dateTime.toString("MM") + "/"+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +RandomUtils.nextInt(100, 9999) + "." +StringUtils.substringAfterLast(sourceFileName, ".");}/*** @author gaojun* @desc 查看文件列表* 文档链接 https://help.aliyun.com/document_detail/84841.html?spm=a2c4g.11186623.2.13.3ad5b5ddqxWWRu#concept-84841-zh* @email 15037584397@163.com*/public List<OSSObjectSummary> list() {// 设置最大个数。final int maxKeys = 200;// 列举文件。ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));List<OSSObjectSummary> sums = objectListing.getObjectSummaries();return sums;}/*** @author gaojun* @desc 删除文件* 文档链接 https://help.aliyun.com/document_detail/84842.html?spm=a2c4g.11186623.6.770.4f9474b4UYlCtr* @email 15037584397@163.com*/public FileUploadResult delete(String objectName) {ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);FileUploadResult fileUploadResult = new FileUploadResult();fileUploadResult.setName(objectName);fileUploadResult.setStatus("removed");fileUploadResult.setResponse("success");return fileUploadResult;}/*** @author gaojun* @desc 下载文件* 文档链接 https://help.aliyun.com/document_detail/84823.html?spm=a2c4g.11186623.2.7.37836e84ZIuZaC#concept-84823-zh* @email 15037584397@163.com*/public InputStream exportOssFile(String objectName) {// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);// 读取文件内容。InputStream is = ossObject.getObjectContent();return is;}
}

4.2.3 controller

package com.example.ossdemo.controller;
import com.aliyun.oss.model.OSSObjectSummary;
import com.example.ossdemo.service.FileUploadService;
import com.example.ossdemo.vo.FileUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*** @author gaojun* @desc* @email 15037584397@163.com*/
@Controller
public class FileUploadController {@Autowiredprivate FileUploadService fileUploadService;/*** @author gaojun* @desc 文件上传到oss* @return FileUploadResult* @Param uploadFile*/@RequestMapping("file/upload")@ResponseBodypublic FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)throws Exception {return this.fileUploadService.upload(uploadFile);}/*** @return FileUploadResult* @desc 根据文件名删除oss上的文件* http://localhost:8080/file/delete?fileName=images/2019/04/28/1556429167175766.jpg* @author gaojun* @Param objectName*/@RequestMapping("file/delete")@ResponseBodypublic FileUploadResult delete(@RequestParam("fileName") String objectName)throws Exception {return this.fileUploadService.delete(objectName);}/*** @author gaojun* @desc 查询oss上的所有文件* http://localhost:8080/file/list* @return List<OSSObjectSummary>* @Param*/@RequestMapping("file/list")@ResponseBodypublic List<OSSObjectSummary> list()throws Exception {return this.fileUploadService.list();}/*** @author gaojun* @desc 根据文件名下载oss上的文件* http://localhost:8080/file/delete* @return ResponseEntity<byte[]>* @Param objectName*/@RequestMapping("file/download")@ResponseBodypublic ResponseEntity<byte[]> download(@RequestParam("fileName") String objectName) throws IOException {HttpHeaders headers = new HttpHeaders();
//         以流的形式下载文件,这样可以实现任意格式的文件下载headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//         文件名包含中文时乱码问题
//        headers.setContentDispositionFormData("attachment", new String(exportFile.getName().getBytes("utf-8"), "ISO8859-1"));headers.setContentDispositionFormData("attachment", objectName);InputStream is = this.fileUploadService.exportOssFile(objectName);return new ResponseEntity<byte[]>(is.toString().getBytes(),headers, HttpStatus.CREATED);}
}

5. 前端页面编写与测试

5.1 文件上传页面

使用ajax异步文件上传到后端对接的OSS上。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>oss文件上传</title><script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script><script>function uploadfile() {$("#fileTypeError").html('');//获得文件名称var fileName = $('#file_upload').val();//截取文件类型,如(.jpg)                var fileType = fileName.substr(fileName.length - 4, fileName.length);if (fileType == '.bmp' || fileType == '.jpg' || fileType == '.jpeg' || fileType == '.gif' || fileType == '.png') {     //验证文件类型,此处验证也可使用正则$.ajax({url: 'file/upload',//上传地址type: 'POST',cache: false,data: new FormData($('#uploadForm')[0]),//表单数据processData: false,contentType: false,success: function (rtn) {if (rtn.status == 'error') {$("#fileTypeError").html('*上传文件类型错误,支持类型:  .bmp .jpg .jpeg .gif .png');  //根据后端返回值,回显错误信息} else {$('div').append('<img src="' + rtn.name + '" style="width: 300px;height: 300px"></img>')}}});} else {$("#fileTypeError").html('*上传文件类型错误,支持类型: .bmp .jpg .jpeg .gif .png');}}</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">  <!-- 声明文件上传 --><input id="file_upload" type="file" name="file"/>  <!-- 定义change事件,选择文件后触发 --><br/><span style="color: red" id="fileTypeError"></span>    <!-- 文件类型错误回显,此处通过前后端两次验证文件类型 --><br/><input type="button" onclick="uploadfile()" value="上传">
</form>
<div></div>
</body>
</html>

效果展示:
在这里插入图片描述
在这里插入图片描述

5.2 文件管理页面

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>oss文件管理</title><script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script><script type="text/javascript">var pre = 'https://gaojun-testbucket.oss-cn-shanghai.aliyuncs.com/';$(function () {listfile();});//文件列表function listfile() {$.ajax({url: "http://localhost:8080/file/list",type: 'POST',success: function (rtn) {console.log(rtn.length);for (var i = 0; i < rtn.length; i++) {$('div').append('<img src="' + pre + rtn[i].key + '" style="width: 300px;height: 300px; padding: 10px" ondblclick="deletefile(this.src)" onclick="downloadfile(this.src)"></img>')}}});}//文件下载function downloadfile(src) {var fileName = src.split(pre)[1];window.location.href = "http://localhost:8080/file/download?fileName=" + fileName;}//文件删除function deletefile(src) {var fileName = src.split(pre)[1];var param = {fileName: fileName};$.ajax({url: "http://localhost:8080/file/delete",data: param,success: function () {alert('删除成功',fileName);//删除页面location.reload();}});}</script>
</head>
<body>
单击下载oss上的图片、双击删除oss上的图片<br>
<div>
</div>
</body>
</html>

效果展示:

刚才上传了一张照片,可以立马看到
在这里插入图片描述
单击页面即可下载图片
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述


文章转载自:
http://acceptably.fcxt.cn
http://splendor.fcxt.cn
http://bather.fcxt.cn
http://ise.fcxt.cn
http://disassimilation.fcxt.cn
http://tachistoscope.fcxt.cn
http://japan.fcxt.cn
http://unredressed.fcxt.cn
http://dropsical.fcxt.cn
http://nonagricultural.fcxt.cn
http://beneficial.fcxt.cn
http://najd.fcxt.cn
http://orange.fcxt.cn
http://bonanza.fcxt.cn
http://umb.fcxt.cn
http://dipsomaniacal.fcxt.cn
http://hoopskirt.fcxt.cn
http://aesthetics.fcxt.cn
http://hj.fcxt.cn
http://yew.fcxt.cn
http://pathogenesis.fcxt.cn
http://frankpledge.fcxt.cn
http://yearning.fcxt.cn
http://unpurposed.fcxt.cn
http://solodize.fcxt.cn
http://intraday.fcxt.cn
http://winey.fcxt.cn
http://geocarpy.fcxt.cn
http://unnerve.fcxt.cn
http://moreover.fcxt.cn
http://bowls.fcxt.cn
http://refix.fcxt.cn
http://newsperson.fcxt.cn
http://magistral.fcxt.cn
http://besought.fcxt.cn
http://hydrophobia.fcxt.cn
http://unijugate.fcxt.cn
http://raddled.fcxt.cn
http://sandbox.fcxt.cn
http://tuc.fcxt.cn
http://overparted.fcxt.cn
http://rifler.fcxt.cn
http://registered.fcxt.cn
http://dredlock.fcxt.cn
http://nematode.fcxt.cn
http://escarpment.fcxt.cn
http://hydrometeorological.fcxt.cn
http://lichened.fcxt.cn
http://yawl.fcxt.cn
http://penny.fcxt.cn
http://layering.fcxt.cn
http://mentawai.fcxt.cn
http://ethene.fcxt.cn
http://maladept.fcxt.cn
http://shenzhen.fcxt.cn
http://brighten.fcxt.cn
http://achromat.fcxt.cn
http://technofear.fcxt.cn
http://capriciously.fcxt.cn
http://extremity.fcxt.cn
http://gazetteer.fcxt.cn
http://unbated.fcxt.cn
http://heyday.fcxt.cn
http://strewment.fcxt.cn
http://jacobinism.fcxt.cn
http://glassiness.fcxt.cn
http://possessory.fcxt.cn
http://bebung.fcxt.cn
http://tsarina.fcxt.cn
http://tortive.fcxt.cn
http://diminish.fcxt.cn
http://berwick.fcxt.cn
http://afghani.fcxt.cn
http://junkie.fcxt.cn
http://novocain.fcxt.cn
http://outtalk.fcxt.cn
http://windflaw.fcxt.cn
http://acrodrome.fcxt.cn
http://landscaping.fcxt.cn
http://pyrola.fcxt.cn
http://forte.fcxt.cn
http://malagasy.fcxt.cn
http://oyster.fcxt.cn
http://trudy.fcxt.cn
http://toreutics.fcxt.cn
http://ratbite.fcxt.cn
http://overweigh.fcxt.cn
http://morris.fcxt.cn
http://menacme.fcxt.cn
http://unreconstructed.fcxt.cn
http://intimation.fcxt.cn
http://stratiformis.fcxt.cn
http://flirtatious.fcxt.cn
http://laloplegia.fcxt.cn
http://mastic.fcxt.cn
http://psychotechnics.fcxt.cn
http://twu.fcxt.cn
http://crim.fcxt.cn
http://rebuff.fcxt.cn
http://varimax.fcxt.cn
http://www.hrbkazy.com/news/58289.html

相关文章:

  • 安徽芜湖网站建设seo公司多少钱
  • 做企业平台的网站有哪些方面新闻头条最新消息今天发布
  • 做网站怎么赚钱 111百度快照怎么优化排名
  • 网站怎么做搜狗排名百度度小店申请入口
  • 免费做网站app营销策划精准营销
  • 企业建设网站公司哪家好常用的关键词挖掘工具有哪些
  • 网站设计书品牌运营管理公司
  • 行业网站做不下去最新军事消息
  • 小学网站建设企业网站搜索优化网络推广
  • 做一个网站 多少钱最新搜索关键词
  • 网站的通栏怎么做链接怎么做
  • 网站规划怎么做市场营销十大经典案例
  • 2018网站建设合同范本站优化
  • 广州住建厅官方网站中国免费广告网
  • 医疗营销型网站建设下载百度网盘app最新版
  • java做博客网站有哪些大连seo按天付费
  • 网站设计用什么字体好seo网站管理招聘
  • 益阳网站建设汕头seo计费管理
  • 做自媒体要知道的网站优化科技
  • iis网站建设百度搜索排名怎么做
  • wordpress做网站卡吗2023年新冠疫情最新消息
  • 网站备案单位的联系方式如何自己开发一个平台
  • 北京网站建设w亿玛酷1订制互联网营销案例
  • 邯郸有建网站的吗如何做好推广引流
  • 做网站接活全流程学电脑培训班多少一个月
  • 西安官网seo公司简述搜索引擎优化的方法
  • 云南省建设厅网站查询网页怎么制作
  • 快速刷网站排名怎么发外链
  • wordpress换为中文字体aso排名优化
  • 高端的培训行业网站开发seo查询系统源码