转载https://www.cnblogs.com/baizhanshi/p/5593431.html

本文介绍如何使用Java实现图片上传至阿里云OSS服务,并获取上传图片的外网URL。涉及HTML表单提交、Spring MVC控制器处理及自定义OSS客户端工具类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传图片到阿里云OSS和获取上传图片的外网url的步骤

啥都不说  直接上代码

1.html:

1

2

3

4

<form action="/bcis/api/headImgUpload.json" method="post" enctype="multipart/form-data">

    <input type="file" name="file">

    <input type="submit" value="提交">

</form>

2.controller:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@RequestMapping(value = "/headImgUpload.json", method = RequestMethod.POST)

 @ResponseBody

 public Map<String, Object> headImgUpload(HttpServletRequest request,MultipartFile file) {

   Map<String, Object> value = new HashMap<String, Object>();

   value.put("success"true);

   value.put("errorCode"0);

   value.put("errorMsg""");

   try {

     String head = userService.updateHead(file, 4);//此处是调用上传服务接口,4是需要更新的userId 测试数据。

     value.put("data", head);

   catch (IOException e) {

     e.printStackTrace();

     value.put("success"false);

     value.put("errorCode"200);

     value.put("errorMsg""图片上传失败");

   }

   return value;

 }

3.service   此处要把

@Autowired
private OSSClientUtil ossClient;注进来

1

2

3

4

5

6

7

8

9

10

@Override

  public String updateHead(MultipartFile file, long userId) throws IOException{

    if (file == null || file.getSize() <= 0) {

      throw new ImgException("头像不能为空");

    }

    String name = ossClient.uploadImg2Oss(file);

    String imgUrl = ossClient.getImgUrl(name);

    userDao.updateHead(userId, imgUrl);//只是本地上传使用的

    return imgUrl;

  }

4.上传的阿里云的帮助类OSSClientUtil 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

import java.io.*;

import java.net.URL;

import java.util.Date;

import java.util.Random;

 

import com.fndsoft.bcis.exception.ImgException;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

 

import com.aliyun.oss.OSSClient;

import com.aliyun.oss.model.ObjectMetadata;

import com.aliyun.oss.model.PutObjectResult;

import org.springframework.util.StringUtils;

import org.springframework.web.multipart.MultipartFile;

 

/**

 * 阿里云 OSS文件类

 *

 * @author YuanDuDu

 */

public class OSSClientUtil {

 

  Log log = LogFactory.getLog(OSSClientUtil.class);

  // endpoint以杭州为例,其它region请按实际情况填写

  private String endpoint = "您的endpoint";

  // accessKey

  private String accessKeyId = "您的accessKeyId";

  private String accessKeySecret = "您的accessKeySecret";

  //空间

  private String bucketName = "bcis";

  //文件存储目录

  private String filedir = "data/";

 

  private OSSClient ossClient;

 

  public OSSClientUtil() {

    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

  }

 

  /**

   * 初始化

   */

  public void init() {

    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

  }

 

  /**

   * 销毁

   */

  public void destory() {

    ossClient.shutdown();

  }

 

  /**

   * 上传图片

   *

   * @param url

   */

  public void uploadImg2Oss(String url) {

    File fileOnServer = new File(url);

    FileInputStream fin;

    try {

      fin = new FileInputStream(fileOnServer);

      String[] split = url.split("/");

      this.uploadFile2OSS(fin, split[split.length - 1]);

    catch (FileNotFoundException e) {

      throw new ImgException("图片上传失败");

    }

  }

 

 

  public String uploadImg2Oss(MultipartFile file) {

    if (file.getSize() > 1024 1024) {

      throw new ImgException("上传图片大小不能超过1M!");

    }

    String originalFilename = file.getOriginalFilename();

    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

    Random random = new Random();

    String name = random.nextInt(10000) + System.currentTimeMillis() + substring;

    try {

      InputStream inputStream = file.getInputStream();

      this.uploadFile2OSS(inputStream, name);

      return name;

    catch (Exception e) {

      throw new ImgException("图片上传失败");

    }

  }

 

  /**

   * 获得图片路径

   *

   * @param fileUrl

   * @return

   */

  public String getImgUrl(String fileUrl) {

    if (!StringUtils.isEmpty(fileUrl)) {

      String[] split = fileUrl.split("/");

      return this.getUrl(this.filedir + split[split.length - 1]);

    }

    return null;

  }

 

  /**

   * 上传到OSS服务器  如果同名文件会覆盖服务器上的

   *

   * @param instream 文件流

   * @param fileName 文件名称 包括后缀名

   * @return 出错返回"" ,唯一MD5数字签名

   */

  public String uploadFile2OSS(InputStream instream, String fileName) {

    String ret = "";

    try {

      //创建上传Object的Metadata 

      ObjectMetadata objectMetadata = new ObjectMetadata();

      objectMetadata.setContentLength(instream.available());

      objectMetadata.setCacheControl("no-cache");

      objectMetadata.setHeader("Pragma""no-cache");

      objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));

      objectMetadata.setContentDisposition("inline;filename=" + fileName);

      //上传文件

      PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);

      ret = putResult.getETag();

    catch (IOException e) {

      log.error(e.getMessage(), e);

    finally {

      try {

        if (instream != null) {

          instream.close();

        }

      catch (IOException e) {

        e.printStackTrace();

      }

    }

    return ret;

  }

 

  /**

   * Description: 判断OSS服务文件上传时文件的contentType

   *

   * @param FilenameExtension 文件后缀

   * @return String

   */

  public static String getcontentType(String FilenameExtension) {

    if (FilenameExtension.equalsIgnoreCase(".bmp")) {

      return "image/bmp";

    }

    if (FilenameExtension.equalsIgnoreCase(".gif")) {

      return "image/gif";

    }

    if (FilenameExtension.equalsIgnoreCase(".jpeg") ||

        FilenameExtension.equalsIgnoreCase(".jpg") ||

        FilenameExtension.equalsIgnoreCase(".png")) {

      return "image/jpeg";

    }

    if (FilenameExtension.equalsIgnoreCase(".html")) {

      return "text/html";

    }

    if (FilenameExtension.equalsIgnoreCase(".txt")) {

      return "text/plain";

    }

    if (FilenameExtension.equalsIgnoreCase(".vsd")) {

      return "application/vnd.visio";

    }

    if (FilenameExtension.equalsIgnoreCase(".pptx") ||

        FilenameExtension.equalsIgnoreCase(".ppt")) {

      return "application/vnd.ms-powerpoint";

    }

    if (FilenameExtension.equalsIgnoreCase(".docx") ||

        FilenameExtension.equalsIgnoreCase(".doc")) {

      return "application/msword";

    }

    if (FilenameExtension.equalsIgnoreCase(".xml")) {

      return "text/xml";

    }

    return "image/jpeg";

  }

 

  /**

   * 获得url链接

   *

   * @param key

   * @return

   */

  public String getUrl(String key) {

    // 设置URL过期时间为10年  3600l* 1000*24*365*10

    Date expiration = new Date(new Date().getTime() + 3600l * 1000 24 365 10);

    // 生成URL

    URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);

    if (url != null) {

      return url.toString();

    }

    return null;

  }

}

### 关于 cnblogs qianfu 博客内容 根据已知的信息,`cnblogs qianfu` 并未直接提及具体的博客内容或作者信息。然而,可以从引用中推测一些可能的方向。例如,在引用[2]中提到的 `Sdcb Chats` 项目是由 `sdcb` 创建并维护的一个开源项目[^2]。虽然这并非来自 `qianfu` 的博客,但它展示了 Cnblogs 上的技术博主通常会分享的内容类型。 Cnblogs 是一个知名的中文技术博客平台,许多开发者会在上面撰写关于编程、算法、框架集成等方面的文章。如果想了解 `qianfu` 的具体博客内容,可以通过以下方式获取更多信息: 1. **访问链接**: 直接打开 [https://www.cnblogs.com/qianfu](https://www.cnblogs.com/qianfu),查看该用户的最新文章列表。 2. **分析主题**: 如果无法直接访问或者需要进一步确认其内容方向,可以根据常见的技术领域猜测,比如 Spring Boot 集成 ElasticSearch[^3] 或者 ACM 算法竞赛中的实现细节[^4]。 以下是基于假设和技术趋势整理的相关知识点示例: #### 示例代码片段 假如 `qianfu` 曾经发布过有关字符串映射处理的教程,则可能会涉及类似的逻辑结构: ```cpp #include <iostream> using namespace std; // 字符串替换函数演示 void replaceString(string& str, const string& from, const string& to) { size_t start_pos = str.find(from); if(start_pos != string::npos) str.replace(start_pos, from.length(), to); } int main(){ string s = "hello world"; replaceString(s,"world","everyone"); cout << s; } ``` 此代码展示了一个简单的字符串替换功能,适用于多种场景下的文本操作需求。 ### 注意事项 由于实际请求的目标站点具体内容未知,以上仅作为理论上的可能性探讨。对于确切的主题范围,请参照目标页面的实际文档说明为准。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值