这里我们讨论两种不同的文件存储方法,一种是利用七牛云(一种云服务器)进行文件存储,另一种则是将文件存储在本地计算机上。
七牛云(每月10G免费额度)
上传方法:
1.首先,你需要在七牛云官网(https://www.qiniu.com/)注册一个账号,并创建一个存储空间。
2.在个人中心->密钥管理中获取自己的AK和SK
3.pom.xml引入依赖
<!--七牛云上传-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.11</version>
</dependency>
<!-- 七牛云依赖Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
4.控制层代码
@PostMapping("/upload")
@ApiOperation("文件上传")
public Result<String> upload(MultipartFile file) throws Exception {
log.info("文件上传{}", file);
byte[] bytes = file.getBytes();
String imageName = UUID.randomUUID().toString();
QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
//使用base64方式上传到七牛云
String imageUrl = qiniuUtil.put64image(bytes, imageName);
return Result.success(imageUrl);
}
5.编写工具类
package com.sky.controller.admin;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.*;
import org.springframework.stereotype.Component;
import static org.springframework.core.io.buffer.DataBufferUtils.readInputStream;
public class QiniuCloudUtil {
// 设置需要操作的账号的AK和SK,第二步查出来的!!!
private static final String ACCESS_KEY = "AK";
private static final String SECRET_KEY = "SK";
// 要上传的空间,这里替换为你第一步创建的存储空间名
private static final String bucketname = "place";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//这里的url替换为对象存储->空间存储->选择你的存储空间(页面右侧CDN测试域名)
private static final String DOMAIN = "url";
//private static final String style = "imageView2/1/w/400/h/400/format/jpg/q/75";
public String getUpToken() {
return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
}
//base64方式上传
public String put64image(byte[] base64, String key) throws Exception{
String file64 = Base64.encodeToString(base64, 0);
Integer l = base64.length;
String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
//非华东空间需要根据注意事项 1 修改上传域名
RequestBody rb = RequestBody.create(null, file64);
Request request = new Request.Builder().
url(url).
addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getUpToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
// 关闭client对象
client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();
// System.out.println(response);
//如果不需要添加图片样式,使用以下方式
return "http://"+DOMAIN +"/"+ key ;
//return DOMAIN + key + "?" + style;
}
}
6.前端接口编码
略
上传到本地
(java文件上传通常使用Servlet和JSP技术实现。如果你使用其他技术,可进行适当修改)
上传方法:
1.创建一个HTML表单,用于选择文件并提交
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
2.创建一个Servlet,用于处理文件上传请求:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
private static final String UPLOAD_DIR = "uploads";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
File uploadDir = new File(getServletContext().getRealPath("") + File.separator + UPLOAD_DIR);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
File uploadFile = new File(uploadDir, fileName);
try (InputStream inputStream = filePart.getInputStream()) {
Files.copy(inputStream, uploadFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("文件上传成功: " + fileName);
}
}