4.0.0
com.qq
fileUploadDownload
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.7.9-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
1.18.16
compile
cn.hutool
hutool-all
5.7.20
server.port=9090
ip=localhost
@SpringBootApplication
public class FileSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(FileSpringBootApplication.class,args);
System.out.println("启动成功");
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private String code;
private String msg;
private Object data;
public static Result success() {
return new Result(Constants.CODE_200, "", null);
}
public static Result success(Object data) {
return new Result(Constants.CODE_200, "", data);
}
public static Result error(String code, String msg) {
return new Result(code, msg, null);
}
public static Result error() {
return new Result(Constants.CODE_500, "系统错误", null);
}
}
public interface Constants {
String CODE_200 = "200"; //成功
String CODE_500 = "500"; // 系统错误
}
import cn.hutool.core.io.FileUtil;
import com.qq.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/file")
public class Filecontroller2 {
@Resource
@Value("${ip:localhost}")
String ip;
@Resource
@Value("${server.port}")
String port;
private static final String ROOT_PATH=System.getProperty("user.dir")+File.separator+"files";
@PostMapping("/upload")
public Result upload(MultipartFile file) throws IOException{
String originalFilename = file.getOriginalFilename();
// String mainName = FileUtil.mainName(originalFilename);文件主体名,比如aaa.jpg,主体名就是aaa
// String extName = FileUtil.extName(originalFilename);//获取文件后缀
if (!FileUtil.exist(ROOT_PATH)){
FileUtil.mkdir(ROOT_PATH);
}
if (FileUtil.exist(ROOT_PATH+File.separator+originalFilename)){
originalFilename=System.currentTimeMillis()+"_"+originalFilename;
}
File saveFile = new File(ROOT_PATH+File.separator+originalFilename);
file.transferTo(saveFile);
String url = "http://"+ip+":"+port+"/file/download/"+originalFilename;
return Result.success(url);
}
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response)throws IOException{
String filePath = ROOT_PATH+File.separator+fileName;
if (!FileUtil.exist(filePath)){
return;
}
byte[] bytes = FileUtil.readBytes(filePath);
ServletOutputStream outputStream = response.getOutputStream();
//设置输出流格式
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//写出流的格式
response.setContentType("application/octet-stream");
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
登录阿里云,搜索OSS对象关系存储,创建Bucket。
com.aliyun.oss
aliyun-sdk-oss
3.15.1
commons-io
commons-io
2.4
commons-beanutils
commons-beanutils
1.9.3
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OssConfig implements InitializingBean {
@Value("${oss.endpoint}")
String endpoint;
@Value("${oss.accessKeyId}")
String accessKeyId;
@Value("${oss.accessKeySecret}")
String accessKeySecret;
@Value("${oss.bucketName}")
String bucketName;
@Value("${oss.fileUrlPrefix}")
String fileUrlPrefix;//阿里域名
//定义公开静态常量
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FILE_URL_PREFIX;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = accessKeyId;
ACCESS_KEY_SECRET = accessKeySecret;
BUCKET_NAME = bucketName;
FILE_URL_PREFIX = fileUrlPrefix;
}
}
import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
public class UploadUtil {
//OSS客户端对象
static OSS ossClient = new OSSClientBuilder().build(OssConfig.END_POIND,OssConfig.ACCESS_KEY_ID,OssConfig.ACCESS_KEY_SECRET);
public static String uploadImage(MultipartFile file)throws IOException{
String originalFilename = file.getOriginalFilename();
String extName = "."+FileUtil.extName(originalFilename);//获取文件后缀
//String extName = "."+ FilenameUtils.getExtension(originalFilename); //获取文件后缀
String uuid= UUID.randomUUID().toString().replace("-","");
String fileName=uuid+extName;
ossClient.putObject(
OssConfig.BUCKET_NAME,//仓库名
fileName,//文件名
file.getInputStream()
);
ossClient.shutdown();
return OssConfig.FILE_URL_PREFIX+fileName;
}
}
一些需要的配置复制的内容如下:
@RestController
public class Filecontroller {
@PostMapping("/upImg")
public String upImg(MultipartFile file) throws IOException{
return UploadUtil.uploadImage(file);
}
}
阿里云中查看文件上传成功
可以参考阿里云开发文档:Java对象/文件_对象存储 OSS-阿里云帮助中心 (aliyun.com)https://help.aliyun.com/zh/oss/developer-reference/objects-8/?spm=a2c4g.11186623.0.0.15254f30U3njhk
参考
使用阿里云OSS实现文件的上传、下载、删除及修改功能_oss下载文件_我代码没错的博客-CSDN博客https://blog.csdn.net/qq_45442178/article/details/130827543?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522169569354716800211513160%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=169569354716800211513160&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~sobaiduend~default-1-130827543-null-null.nonecase&utm_term=%E9%98%BF%E9%87%8C%E4%BA%91oss%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6&spm=1018.2226.3001.4450