资源类存储
1、springboot+mongodb
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
server.port=8090
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/file
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
@Data
@Document
@Accessors(chain = true)
public class UploadFile {
@Id
private String id;
private String name;
private LocalDateTime createdTime;
private Binary content;
private String contentType;
private long size;
public UploadFile(){
this.id = UUID.randomUUID().toString().substring(0,32);
}
}
@Data
@Accessors(chain = true)
public class JSONResult<T> implements Serializable {
private Integer code;
private String msg;
private T data;
public static <T> JSONResult<T> build(int code, String msg, T data) {
return new JSONResult<T>()
.setCode(code)
.setMsg(msg)
.setData(data);
}
}
@RestController
@RequestMapping("/db")
public class MongoDBController {
public static String getCollection(String name){
return "fileCollection_"+name;
}
@Autowired
private MongoTemplate mongoTemplate;
@Value("${server.port}")
private String port;
@PostMapping("/upload")
public JSONResult<String> uploadImage(@RequestParam("file")MultipartFile file){
JSONResult<String> jsonResult = null;
try {
UploadFile uploadFile = new UploadFile()
.setContentType(file.getContentType().split("/")[1])
.setName(file.getOriginalFilename())
.setCreatedTime(LocalDateTime.now())
.setContent(new Binary(file.getBytes()))
.setSize(file.getSize());
UploadFile savedFile = mongoTemplate.save(uploadFile, getCollection("photo"));
String url = "localhost:"+ port +"/db/image/show/"+savedFile.getId()+"/photo";
if (file.getOriginalFilename().contains("mp4")){
url = "localhost:"+ port +"/db/movie/show/"+savedFile.getId()+"/photo";
}
jsonResult = JSONResult.build(200, "图片上传成功", url);
} catch (Exception e) {
e.printStackTrace();
jsonResult = JSONResult.build(500,"图片上传失败",null);
}
return jsonResult;
}
@GetMapping("/movie/show/{id}/{name}")
public void movieLoad(@PathVariable("id") String id,
@PathVariable("name") String name,
HttpServletResponse response) throws Exception{
UploadFile file = mongoTemplate.findById(id, UploadFile.class, getCollection(name));
response.setContentType("video/mp4");
OutputStream outputStream = response.getOutputStream();
outputStream.write(file.getContent().getData());
outputStream.flush();
}
@GetMapping(value = "/image/show/{id}/{name}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
public byte[] loadImage(@PathVariable("id") String id,
@PathVariable("name") String name){
List<UploadFile> fileList = mongoTemplate.find(new Query(Criteria.where("_id").is(id)),UploadFile.class,getCollection(name));
byte[] data = null;
data = fileList.get(0).getContent().getData();
return data;
}
@GetMapping(value = "/image/out/{id}/{name}")
public void outImage(@PathVariable("id") String id,
@PathVariable("name") String name,
HttpServletResponse response) throws IOException{
List<UploadFile> fileList = mongoTemplate.find(new Query(Criteria.where("_id").is(id)),UploadFile.class,getCollection(name));
byte[] data = fileList.get(0).getContent().getData();
response.setContentType("image/jpeg");
ServletOutputStream outputStream = response.getOutputStream();
BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(image,"png",outputStream);
}
@GetMapping("/image/local/{id}/{name}")
public String loadLocal(@PathVariable("id") String id,
@PathVariable("name") String name) throws IOException {
UploadFile file = mongoTemplate.findById(id,UploadFile.class,getCollection(name));
File file1 = new File("D:\\temp\\movies\\"+file.getName());
if (file1.exists()){
file1.delete();
}
file1.createNewFile();
OutputStream outputStream = new FileOutputStream(file1);
outputStream.write(file.getContent().getData());
return "ok";
}
}
<!DOCTYPE html>
<html>
<head>
<title>db</title>
</head>
<body>
<div>
<form method="post" enctype="multipart/form-data" action="/db/upload">
<table>
<tr>
<td>File to upload:</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>视频展示</title>
</head>
<body>
<div>
<video width="1120" height="540" controls="controls" id="video" preload="auto">
<source src="/db/movie/show/d0f1c295-e8f5-485d-b594-5e2a07a8/photo" type="video/mp4">
</video>
</div>
</body>
</html>
2、springboot+OSS(阿里OSS对象存储)
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
@Data
@Document
@Accessors(chain = true)
public class LoadFile {
@Id
private String id;
private String filePath;
private String name;
private LocalDateTime createdTime;
private InputStream content;
private String contentType;
private long size;
}
@Component
public class Aliyun {
@Autowired
private RestTemplate restTemplate;
private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";
private static String accessKeyId = "******";
private static String accessKeySecret = "******";
private static String bucketName = "******";
public String upload(LoadFile file, String url) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String key = file.getFilePath() + "/" + file.getName();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getContent());
String result = restTemplate.getForObject(url, String.class, file.getName(), file.getFilePath());
ossClient.putObject(putObjectRequest);
ossClient.shutdown();
return result;
}
public byte[] load(String key) throws IOException {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(bucketName, key);
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
StringBuffer buffer = new StringBuffer();
while (true) {
String line = reader.readLine();
buffer.append(line);
if (line == null) {
break;
}
}
byte[] data = buffer.toString().getBytes(Charset.defaultCharset());
reader.close();
ossClient.shutdown();
return data;
}
public void loadLocal(String key) throws IOException {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
File file = new File("D:\\temp\\" + key);
if (file.exists()) {
file.delete();
}
file.createNewFile();
ossClient.getObject(new GetObjectRequest(bucketName, key), file);
ossClient.shutdown();
}
}
@RestController
@RequestMapping("/oss")
public class OSSController {
@Autowired
Aliyun aliyun;
@Autowired
RestTemplate restTemplate;
@PostMapping("/image/upload")
public JSONResult<String> upload(@RequestParam("file")MultipartFile file) throws Exception{
LoadFile loadFile = new LoadFile()
.setFilePath("movie")
.setName(file.getOriginalFilename())
.setContent(file.getInputStream());
String url = "http://localhost:8090/oss/load/"+file.getOriginalFilename()+"/"+loadFile.getFilePath();
String result = aliyun.upload(loadFile, url);
JSONResult<String> jsonResult = JSONResult.build(200, result,url);
return jsonResult;
}
@GetMapping(value = "/load/{name}/{path}")
public String load(@PathVariable("name")String name,
@PathVariable("path")String path) throws Exception{
aliyun.loadLocal(path + "/" + name);
return "生成文件已经下载直本地D:/temp"+path+"/"+name;
}
}
- 可能restTemplat会出错
- RestTemplateConfig
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
<!DOCTYPE html>
<html>
<head>
<title>oss</title>
</head>
<body>
<div>
<form method="post" enctype="multipart/form-data" action="/oss/image/upload">
<table>
<tr>
<td>File to upload:</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
@Controller
public class RouteController {
@GetMapping("/image")
public String uploadImage(){return "imageUpload";}
@GetMapping("movie")
public String uploadMovie(){return "movies";}
@GetMapping("/oss/image")
public String uploadOSSImage(){return "ossUpload";}
@GetMapping("/oss/movie")
public String uploadOSSMovie(){return "OOSMovies";}
}
|