When using the Springboot framework to make a website, often upload some files such as images. The first method is to transfer the image to Base64 encoding and store it in the database, and the fields can be stored by longtext and other types. The second method is to use OSS server for storage, directly go to Ali Cloud OSS purchase (if you do not want to spend money, can be transferred to Qiuniuyun OSS).
Introduction on the official website of Ali Cloud OSS: Ali Cloud Object Storage Service (OSS) is a massive, secure, low-cost and highly reliable cloud Storage Service provided by Ali Cloud. You can upload and download data at any time, anywhere, and on any Internet device using the simple REST interface provided in this document. Based on OSS, you can build a variety of multimedia sharing websites, web disks, personal and enterprise data backup services based on large-scale data.
Import dependencies
<! -- Ali Cloud OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.5.0</version>
</dependency>
Copy the code
2. Create a configuration file
In the same directory as the application.properties file, create aliyun.properties with five fields.
These 5 fields are directly available in the OSS server.
aliyun.access-id=
aliyun.access-key=
aliyun.bucket=
aliyun.endpoint=
aliyun.dir=
Copy the code
Create a properties file reading class
If you don’t want to use this class, you can just change it to static.
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:/aliyun.properties")
public class OSSProperties implements InitializingBean {
@Value("${aliyun.endpoint}")
private String aliyun_endpoint;
@Value("${aliyun.access-id}")
private String aliyun_access_id;
@Value("${aliyun.access-key}")
private String aliyun_access_key;
@Value("${aliyun.bucket}")
private String aliyun_bucket;
@Value("${aliyun.dir}")
private String aliyun_dir;
// Declare static variables
public static String ALIYUN_ENDPOINT;
public static String ALIYUN_ACCESS_ID;
public static String ALIYUN_ACCESS_KEY;
public static String ALIYUN_BUCKET;
public static String ALIYUN_DIR;
@Override
public void afterPropertiesSet(a) { ALIYUN_ENDPOINT = aliyun_endpoint; ALIYUN_ACCESS_ID = aliyun_access_id; ALIYUN_ACCESS_KEY = aliyun_access_key; ALIYUN_BUCKET = aliyun_bucket; ALIYUN_DIR = aliyun_dir; }}Copy the code
OSSUtil utility classes
Pictures can be deleted, uploaded, view url links and so on.
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
public class OSSUtil {
/** * log */
public static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
private final String endpoint = OSSProperties.ALIYUN_ENDPOINT;
private final String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;
private final String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;
private final String bucketName = OSSProperties.ALIYUN_BUCKET;
private final String FOLDER = OSSProperties.ALIYUN_DIR;
/** * delete a single image **@param url
*/
public void deleteImg(String url) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
url = FOLDER + url;
ossClient.deleteObject(bucketName, url);
System.out.println("Delete" + url + "Success");
ossClient.shutdown();
}
/** * upload image **@param file
* @param fileName
* @return
* @throws IOException
*/
public String uploadImg2Oss(MultipartFile file, String fileName) throws IOException {
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, fileName);
String url = "https://" + bucketName + "." + endpoint + "/" + FOLDER + fileName;
return url;
} catch (Exception e) {
throw new IOException("Picture uploading failed"); }}/** * Uploading files with the same name to the OSS server will overwrite ** on the server@paramInstream file stream *@paramFileName specifies the fileName. The fileName extension is *@returnError return "", unique MD5 digital signature */
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// Create Metadata to upload Object
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);
// Upload the file
PutObjectResult putResult = ossClient.putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
// logger.error(e.getMessage(), e);
System.out.println(e.getMessage());
} finally {
try {
if(instream ! =null) { instream.close(); }}catch(IOException e) { e.printStackTrace(); }}return ret;
}
/** * Description: Determines the contentType */ of the OSS service file when it is uploaded
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";
}
/** * get the url **@param key
* @return* /
public String getUrl(String key) {
// Set the URL expiration time to 10 years 3600L * 1000*24*365*10
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
/ / generated URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
// url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + bucketName+"/"+ key;
if(url ! =null) {
String host = "https://" + url.getHost() + url.getPath();
return host;
}
return ""; }}Copy the code
Five, the call
The UUID method is used to ensure that the file name is not duplicated.
@PostMapping
public Result upload(@RequestParam("image") MultipartFile file) throws IOException {
// The original file name, for example, a.png
String originalFilename = file.getOriginalFilename();
// A unique file name
String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
// Upload the address
OSSUtil ossUtil = new OSSUtil();
String url = ossUtil.uploadImg2Oss(file, fileName);
if(url ! =null) {
return Result.success(url);
}
return Result.fail(20001."Upload failed");
}
Copy the code