pom.xml
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
</properties>
<dependencies>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--腾讯云-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
<!-- 文件上传所依赖的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
COSClientUtil.java
package com.neusoft.util;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;
/**
* @author XiaoLuo
* @ClassName: com.neusoft.controller.util.COSClientUtil
* @Description: ${todo}
* @date 2018/3/12 15:37
*/
public class COSClientUtil {
//todo 这些变量信息自行到 腾讯云对象存储控制台 获取
// 存储通名称 替换成自己的
private static final String bucketName = "storage-1254279902";
//secretId 替换成自己的
private static final String secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// secretKey 替换成自己的
private static final String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// 1 初始化用户身份信息(secretId, secretKey)
private static final COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
// 3 生成cos客户端
private static final COSClient cosClient = new COSClient(cred, clientConfig);
// 文件存储目录
//private String filedir = "blog/";
private COSClient cOSClient;
public COSClientUtil() {
cOSClient = new COSClient(cred, clientConfig);
}
/**
* 销毁
*/
public void destory() {
cOSClient.shutdown();
}
/**
* 上传图片
*
* @param url
*/
public void uploadImg2Cos(String url) throws Exception {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2Cos(fin, split[split.length - 1]);
} catch (FileNotFoundException e) {
throw new Exception("图片上传失败");
}
}
public String uploadFile2Cos(MultipartFile file) throws Exception {
if (file.getSize() > 10 * 1024 * 1024) {
throw new Exception("上传图片大小不能超过10M!");
}
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.uploadFile2Cos(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("图片上传失败");
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
return getUrl(fileUrl);
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
/**
* 上传到COS服务器 如果同名文件会覆盖服务器上的
*
* @param instream
* 文件流
* @param fileName
* 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2Cos(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 = cOSClient.putObject(bucketName, fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* Description: 判断Cos服务文件上传时文件的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";
}
}
UploadController.java
package com.neusoft.controller;
import com.neusoft.util.COSClientUtil;
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 org.springframework.web.servlet.ModelAndView;
/**
* @author XiaoLuo
* @ClassName: UserController
* @Description: ${todo}
* @date 2017/9/1 17:57
*/
@Controller
public class UploadController {
@RequestMapping("/")
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping("/upload")
@ResponseBody
public Object upload(@RequestParam("file") MultipartFile file)throws Exception{
COSClientUtil cosClientUtil = new COSClientUtil();
String name = cosClientUtil.uploadFile2Cos(file);
String imgUrl = cosClientUtil.getImgUrl(name);
String[] split = imgUrl.split("\\?");
return split[0];
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input id="file" type="file" name="file"/>
<br><br><br>
<button id="upload" type="button" οnclick="uploadImg()" >测试上传图片到腾讯云</button>
</form>
<script>
/*
ajax文件上传教程:
https://blog.csdn.net/inuyasha1121/article/details/51915742
*/
function uploadImg() {
debugger
$.ajax({
type: "post",
url: '/upload',
data: new FormData($('#uploadForm')[0]),
processData: false,
contentType: false,
success: function (data) {
alert(data)
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败!");
}
});
}
</script>
</body>
</html>
整个案例工程已上传到CSDN,
点击打开链接。