Project screenshots
The material, as well as some key code implementation reference link: an album on the cloud
Project implementation
Introduction to the
Cloud photo is a personal cloud album based on springboot framework, which can realize simple local photo storage. The photos stored by end users will be stored in Tencent cloud storage bucket. For details of uploading, please refer to uploading photos to Tencent cloud storage bucket
This blogger focuses on describing the technical implementation in the project process.
Qq Mail function
This project realizes the activation of account in the form of QQ email.
The design of some user tables in the database:
STATUS stands for account activation. After successful registration, users will receive a QQ email and click the QQ email to activate the account. The information stored in STATUS is also N->Y, indicating successful account activation (of course, the verification code can also be used to achieve the same general logic).
Some of the implementation of the entity class bloggers will not be described here, the source has been put in the end
Implementation process:
Introduction of depend on
<! -- third-party library for file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
Copy the code
MailUtils class
public final class MailUtils {
//20b30176d4526d69
private static final String USER = "[email protected]"; // Sender name, same as email address
private static final String PASSWORD = ""; // If you use qq email, you can use the authorization code or login password. The method of obtaining the authorization code is described below
/ * * *@paramTo Recipient email *@paramText Email body *@paramThe title title * /
/* Send an email with authentication information */
public static boolean sendMail(String to, String text, String title) {
try {
final Properties props = new Properties();
props.put("mail.smtp.auth"."true");
props.put("mail.smtp.host"."smtp.qq.com");
// Sender's account
props.put("mail.user", USER);
// Sender's password
props.put("mail.password", PASSWORD);
// Build authorization information for SMTP authentication
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication(a) {
// User name and password
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return newPasswordAuthentication(userName, password); }};// Create a mail session using the environment properties and authorization information
Session mailSession = Session.getInstance(props, authenticator);
// Create a mail message
MimeMessage message = new MimeMessage(mailSession);
// Set the sender
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// Set the recipient
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// Set the message title
message.setSubject(title);
// Set the body of the message
message.setContent(text, "text/html; charset=UTF-8");
// Send an email
Transport.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception { // For testing purposes
MailUtils.sendMail("@qq.com"."Doggie? Go to bed early and have a good night. Don't miss don't reply."."Test mail");
System.out.println("Sent successfully"); }}Copy the code
Obtain qq mailbox authorization code
Image upload part of the code to achieve
The front part
home.html
<form id="fileForm" action="/image/upload" onsubmit="return checkFileSize()" method="post"
enctype="multipart/form-data" class="navbar-form navbar-left">
<div class="form-group" style="border-color: #3c3c3c">
<input id="files" class="form-control" type="file" name="upload" multiple required>
<input type="submit" class="btn btn-success" value="Upload"/>
</div>
</form>
Copy the code
The backend part
@PostMapping("/upload")
public void upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//1. Do your homework and get the Upload object that can parse the request
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items;
try {
//1.1 Parse the request, obtain the file item list, key code implementation
items = upload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
// Failed to parse the request object
resp.sendRedirect("/user/error");
return;
}
// Iterate through the file entry to make sure there are no files that are not images
for (FileItem item : items) {
if(! item.getContentType().contains("image")) {
// The image uploaded by the user is not a picture
resp.sendRedirect("/user/error");
return; }}// Get the login information from the session
User user = (User) (req.getSession().getAttribute("user"));
// Start processing files
for (FileItem item : items) {
//2. Encapsulate the Image object
Image image = new Image();
image.setUid(user.getId());
//2.1 Formatting the Upload time
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
image.setUploadTime(format.format(new Date()));
//2.2 Get the file name
image.setImageName(parseFileName(item.getName()));
image.setContentType(item.getContentType());
//2.3 Using MD5, use binary data of image to calculate MD5 plus password, can save disk space when storing the same image in the future
image.setMd5(DigestUtils.md2Hex(item.get()));
//2.4 Set the path, MD5 can prevent overwriting the image
//3. Write to the disk first (before writing, the database will check whether there is any data, if there is no data, the picture can be written to Tencent cloud storage bucket for the first time)
//3.1 Obtaining the project deployment path
/*File file = new File(image.getPath()); * /
try {
// Check if the image exists in the database before writing to disk
Image imageByMD5 = imageService.findImageByMD5(image.getMd5(), user.getId());
if (imageByMD5 == null) {
// The image is not in the database, which means it is the first time to store, and then we write the cloud storage bucket
/* item.write(file); * /This interface is used to write to the local disk. You can select the interface as required// Turn FIleItem into File
File toFile = new File(image.getImageName());
item.write(toFile);
// Upload to Tencent cloud storage bucket
String fileName = TencentCOS.uploadfile(toFile);// See the link in the introduction above
image.setPath(fileName);// fileName indicates the path in the cloud storage bucket
image.setSize((int) item.getSize());
}
//4. Records in the database are written to the disk regardless of whether the data is written to the disk
imageService.insertImage(image);
} catch (Exception e) {
e.printStackTrace();
Error writing to disk
resp.sendRedirect("/user/error");
return; }}// Because it is multi-file, redirection will be done after all files are processed
// Here we can redirect the refresh page
resp.sendRedirect(req.getContextPath() + "/user/home");
}
Copy the code
Some of the MD5 encryption authors in the code will not be described here
The tencentcos.upload () function in the code is implemented right in the blogger’s introduction link.
Picture shows part of the code implementation
The front part
<div v-for="image in images" style="border-radius: 15%">
<img id="sImage" style="border-radius: 10%; width: 200px; height: 200px;"
v-bind:src="'/image/show? imageId='+image.imageId" v-on:click="showBigImage(image.imageId)"
alt="Pictures are loading like crazy.">
<font style="font-family: SimSun; font-size: 12px">{{image.imageName}}</font><br/>
<font style="font-family: SimSun; font-size: 12px">{{image.uploadTime}}</font><br/>
<button style="border-radius: 100%; background-color: aquamarine; float: left"
v-on:click.stop="deleteImage(image.imageId)">abandon</button>
<button style="border-radius: 100%; background-color: aquamarine; float: right;" v-on:click.stop="downloadImage(image.imageId)">pick</button>
</div>
Copy the code
The backend part
@GetMapping("/show")
public void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ResultInfo info = new ResultInfo();
// Get the current user ID
User user = (User) (req.getSession().getAttribute("user"));
//1. Obtain the imageId of the request parameter and query the image based on the parameter
String imageId = req.getParameter("imageId");
if (imageId == null || "".equals(imageId)) {
// imageId cannot be accessed without changing its value
info.setFlag(false);
info.setErrorMsg("Inaccessible due to mysterious force interference.");
writeValue(info, resp);
return;
}
Image image = imageService.findByImageId(Integer.parseInt(imageId), user.getId());
// Outputs the byte stream to the browser
//File file = new File(image.getPath());
byte[] buffer = new byte[1024 * 20];
//1. Create an input stream to write to the buffer
/* BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); * /// Write the input stream from the local file to the cache
BufferedInputStream in = new BufferedInputStream(TencentCOS.showFile(image.getPath()));
//2. Create an output stream to output data
// remember to set the type, otherwise failure will be displayed
resp.setContentType(image.getContentType());
BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());
while (true) {
int len = in.read(buffer);
if (len == -1) {
// Data has been read
break;
} else {
out.write(buffer);// Write the byte stream to the page and the img tag will display the image}}// Remember to close
in.close();
out.close();
}
Copy the code
As to delete pictures and download pictures to the local function of the blogger here is no longer detailed, interested partners can download the source code of this procedure, due to the blogger is also a reference to other people’s code implementation, so partners cite when please indicate the source. (Attached with source code download address)
Program source code
Source link to gitee repository