Skip to content

Latest commit

History

History

demo-upload

Folders and files

NameName
Last commit message
Last commit date

parent directory

..

spring-boot-demo-upload

Bổn demo biểu thị Spring Boot như thế nào thực hiện bản địa văn kiện thượng truyền cùng với như thế nào thượng truyền văn kiện đến bảy ngưu vân ngôi cao. Đằng trước sử dụng vue cùng iview thực hiện thượng truyền giao diện.

pom.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http:// w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-boot-demo-upload</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring-boot-demo-upload</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>com.xkcoding</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>

<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
</dependencies>

<build>
<finalName>spring-boot-demo-upload</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

UploadConfig.java

/**
* <p>
* thượng truyền phối trí
* </p>
*
* @author yangkai.shen
* @date Created in 2018-10-23 14:09
*/
@Configuration
@ConditionalOnClass({Servlet.class,StandardServletMultipartResolver.class,MultipartConfigElement.class})
@ConditionalOnProperty(prefix="spring.http.multipart",name="enabled",matchIfMissing=true)
@EnableConfigurationProperties(MultipartProperties.class)
publicclassUploadConfig{
@Value("${qiniu.accessKey}")
privateStringaccessKey;

@Value("${qiniu.secretKey}")
privateStringsecretKey;

privatefinalMultipartPropertiesmultipartProperties;

@Autowired
publicUploadConfig(MultipartPropertiesmultipartProperties) {
this.multipartProperties=multipartProperties;
}

/**
* thượng truyền phối trí
*/
@Bean
@ConditionalOnMissingBean
publicMultipartConfigElementmultipartConfigElement() {
returnthis.multipartProperties.createMultipartConfig();
}

/**
* đăng ký phân tích khí
*/
@Bean(name=DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
@ConditionalOnMissingBean(MultipartResolver.class)
publicStandardServletMultipartResolvermultipartResolver() {
StandardServletMultipartResolvermultipartResolver=newStandardServletMultipartResolver();
multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
returnmultipartResolver;
}

/**
* Hoa Đông phòng máy tính
*/
@Bean
publiccom.qiniu.storage.ConfigurationqiniuConfig() {
returnnewcom.qiniu.storage.Configuration(Zone.zone0());
}

/**
* xây dựng một cái bảy ngưu thượng truyền công cụ ví dụ thực tế
*/
@Bean
publicUploadManageruploadManager() {
returnnewUploadManager(qiniuConfig());
}

/**
* chứng thực tin tức ví dụ thực tế
*/
@Bean
publicAuthauth() {
returnAuth.create(accessKey,secretKey);
}

/**
* xây dựng bảy ngưu không gian quản lý ví dụ thực tế
*/
@Bean
publicBucketManagerbucketManager() {
returnnewBucketManager(auth(),qiniuConfig());
}
}

UploadController.java

/**
* <p>
* văn kiện thượng truyền Controller
* </p>
*
* @author yangkai.shen
* @date Created in 2018-11-06 16:33
*/
@RestController
@Slf4j
@RequestMapping("/upload")
publicclassUploadController{
@Value("${spring.servlet.multipart.location}")
privateStringfileTempPath;

@Value("${qiniu.prefix}")
privateStringprefix;

privatefinalIQiNiuServiceqiNiuService;

@Autowired
publicUploadController(IQiNiuServiceqiNiuService) {
this.qiNiuService=qiNiuService;
}

@PostMapping(value="/local",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
publicDictlocal(@RequestParam("file")MultipartFilefile) {
if(file.isEmpty()) {
returnDict.create().set("code",400).set("message","Văn kiện nội dung vì không");
}
StringfileName=file.getOriginalFilename();
StringrawFileName=StrUtil.subBefore(fileName,".",true);
StringfileType=StrUtil.subAfter(fileName,".",true);
StringlocalFilePath=StrUtil.appendIfMissing(fileTempPath,"/") +rawFileName+"-"+DateUtil.current(false) +"."+fileType;
try{
file.transferTo(newFile(localFilePath));
}catch(IOExceptione) {
log.error("【 văn kiện thượng truyền đến bản địa 】 thất bại, tuyệt đối đường nhỏ: {}",localFilePath);
returnDict.create().set("code",500).set("message","Văn kiện thượng truyền thất bại");
}

log.info("【 văn kiện thượng truyền đến bản địa 】 tuyệt đối đường nhỏ: {}",localFilePath);
returnDict.create().set("code",200).set("message","Thượng truyền thành công").set("data",Dict.create().set("fileName",fileName).set("filePath",localFilePath));
}

@PostMapping(value="/yun",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
publicDictyun(@RequestParam("file")MultipartFilefile) {
if(file.isEmpty()) {
returnDict.create().set("code",400).set("message","Văn kiện nội dung vì không");
}
StringfileName=file.getOriginalFilename();
StringrawFileName=StrUtil.subBefore(fileName,".",true);
StringfileType=StrUtil.subAfter(fileName,".",true);
StringlocalFilePath=StrUtil.appendIfMissing(fileTempPath,"/") +rawFileName+"-"+DateUtil.current(false) +"."+fileType;
try{
file.transferTo(newFile(localFilePath));
Responseresponse=qiNiuService.uploadFile(newFile(localFilePath));
if(response.isOK()) {
JSONObjectjsonObject=JSONUtil.parseObj(response.bodyString());

StringyunFileName=jsonObject.getStr("key");
StringyunFilePath=StrUtil.appendIfMissing(prefix,"/") +yunFileName;

FileUtil.del(newFile(localFilePath));

log.info("【 văn kiện thượng truyền đến bảy ngưu vân 】 tuyệt đối đường nhỏ: {}",yunFilePath);
returnDict.create().set("code",200).set("message","Thượng truyền thành công").set("data",Dict.create().set("fileName",yunFileName).set("filePath",yunFilePath));
}else{
log.error("【 văn kiện thượng truyền đến bảy ngưu vân 】 thất bại, {}",JSONUtil.toJsonStr(response));
FileUtil.del(newFile(localFilePath));
returnDict.create().set("code",500).set("message","Văn kiện thượng truyền thất bại");
}
}catch(IOExceptione) {
log.error("【 văn kiện thượng truyền đến bảy ngưu vân 】 thất bại, tuyệt đối đường nhỏ: {}",localFilePath);
returnDict.create().set("code",500).set("message","Văn kiện thượng truyền thất bại");
}
}
}

QiNiuServiceImpl.java

/**
* <p>
* bảy ngưu vân thượng truyền Service
* </p>
*
* @author yangkai.shen
* @date Created in 2018-11-06 17:22
*/
@Service
@Slf4j
publicclassQiNiuServiceImplimplementsIQiNiuService,InitializingBean{
privatefinalUploadManageruploadManager;

privatefinalAuthauth;

@Value("${qiniu.bucket}")
privateStringbucket;

privateStringMapputPolicy;

@Autowired
publicQiNiuServiceImpl(UploadManageruploadManager,Authauth) {
this.uploadManager=uploadManager;
this.auth=auth;
}

/**
* bảy ngưu vân thượng truyền văn kiện
*
* @param file văn kiện
* @return bảy ngưu thượng truyền Response
* @throws QiniuException bảy ngưu dị thường
*/
@Override
publicResponseuploadFile(Filefile)throwsQiniuException{
Responseresponse=this.uploadManager.put(file,file.getName(),getUploadToken());
intretry=0;
while(response.needRetry() &&retry<3) {
response=this.uploadManager.put(file,file.getName(),getUploadToken());
retry++;
}
returnresponse;
}

@Override
publicvoidafterPropertiesSet() {
this.putPolicy=newStringMap();
putPolicy.put("returnBody","{\ "key\ ":\ "$(key)\ ",\ "hash\ ":\ "$(etag)\ ",\ "bucket\ ":\ "$(bucket)\ ",\ "width\ ":$(imageInfo.width),\ "height\ ":${imageInfo.height}} ");
}

/**
* thu hoạch thượng truyền bằng chứng
*
* @return thượng truyền bằng chứng
*/
privateStringgetUploadToken() {
returnthis.auth.uploadToken(bucket,null,3600,putPolicy);
}
}

index.html

<!doctype html>
<htmllang= "en">
<head>
<metacharset= "UTF-8">
<metaname= "viewport"
content= "width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<metahttp-equiv= "X-UA-Compatible"content= "ie=edge">
<title>spring-boot-demo-upload</title>
<!-- import Vue.js -->
<scriptsrc= "https://cdn.bootcss /vue/2.5.17/vue.min.js"></script>
<!-- import stylesheet -->
<linkhref= "https://cdn.bootcss /iview/3.1.4/styles/iview.css"rel= "stylesheet">
<!-- import iView -->
<scriptsrc= "https://cdn.bootcss /iview/3.1.4/iview.min.js"></script>
</head>
<body>
<divid= "app">
<Row:gutter= "16"style= "background:#eee;padding:10%">
<i-colspan= "12">
<Cardstyle= "height: 300px">
<pslot= "title">
<Icontype= "ios-cloud-upload"></Icon>
Bản địa thượng truyền
</p>
<divstyle= "text-align: center;">
<Upload
:before-upload= "handleLocalUpload"
action= "/demo/upload/local"
ref= "localUploadRef"
:on-success= "handleLocalSuccess"
:on-error= "handleLocalError"
>
<i-buttonicon= "ios-cloud-upload-outline">Lựa chọn văn kiện</i-button>
</Upload>
<i-button
type= "primary"
@click= "localUpload"
:loading= "local.loadingStatus"
:disabled= "!local.file">
{{ local.loadingStatus? ' bản địa văn kiện thượng truyền trung ': ' bản địa thượng truyền ' }}
</i-button>
</div>
<div>
<divv-if= "local.log.status!= 0">Trạng thái: {{local.log.message}}</div>
<divv-if= "local.log.status === 200">Văn kiện danh: {{local.log.fileName}}</div>
<divv-if= "local.log.status === 200">Văn kiện đường nhỏ: {{local.log.filePath}}</div>
</div>
</Card>
</i-col>
<i-colspan= "12">
<Cardstyle= "height: 300px;">
<pslot= "title">
<Icontype= "md-cloud-upload"></Icon>
Bảy ngưu vân thượng truyền
</p>
<divstyle= "text-align: center;">
<Upload
:before-upload= "handleYunUpload"
action= "/demo/upload/yun"
ref= "yunUploadRef"
:on-success= "handleYunSuccess"
:on-error= "handleYunError"
>
<i-buttonicon= "ios-cloud-upload-outline">Lựa chọn văn kiện</i-button>
</Upload>
<i-button
type= "primary"
@click= "yunUpload"
:loading= "yun.loadingStatus"
:disabled= "!yun.file">
{{ yun.loadingStatus? ' bảy ngưu vân văn kiện thượng truyền trung ': ' bảy ngưu vân thượng truyền ' }}
</i-button>
</div>
<div>
<divv-if= "yun.log.status!= 0">Trạng thái: {{yun.log.message}}</div>
<divv-if= "yun.log.status === 200">Văn kiện danh: {{yun.log.fileName}}</div>
<divv-if= "yun.log.status === 200">Văn kiện đường nhỏ: {{yun.log.filePath}}</div>
</div>
</Card>
</i-col>
</Row>
</div>
<script>
newVue({
el:'#app',
data:{
local:{
// lựa chọn văn kiện sau, đem beforeUpload phản hồi file bảo tồn ở chỗ này, mặt sau sẽ dùng đến
file:null,
// đánh dấu thượng truyền trạng thái
loadingStatus:false,
log:{
status:0,
message:"",
fileName:"",
filePath:""
}
},
yun:{
// lựa chọn văn kiện sau, đem beforeUpload phản hồi file bảo tồn ở chỗ này, mặt sau sẽ dùng đến
file:null,
// đánh dấu thượng truyền trạng thái
loadingStatus:false,
log:{
status:0,
message:"",
fileName:"",
filePath:""
}
}
},
methods:{
// beforeUpload ở phản hồi false hoặc Promise khi, sẽ đình chỉ tự động thượng truyền, nơi này chúng ta đem lựa chọn tốt văn kiện file bảo tồn ở data, cũng return false
handleLocalUpload(file){
this.local.file=file;
returnfalse;
},
// nơi này là tay động thượng truyền, thông qua $refs thu hoạch đến Upload ví dụ thực tế, sau đó thuyên chuyển tư hữu phương pháp.post(), đem bảo tồn ở data file thượng truyền.
// iView Upload lắp ráp ở thuyên chuyển.post() phương pháp khi, liền sẽ tiếp tục thượng truyền.
localUpload(){
this.local.loadingStatus=true;// đánh dấu thượng truyền trạng thái
this.$refs.localUploadRef.post(this.local.file);
},
// thượng truyền thành công sau, quét sạch data file, cũng sửa chữa thượng truyền trạng thái
handleLocalSuccess(response){
this.local.file=null;
this.local.loadingStatus=false;
if(response.code===200){
this.$Message.success(response.message);
this.local.log.status=response.code;
this.local.log.message=response.message;
this.local.log.fileName=response.data.fileName;
this.local.log.filePath=response.data.filePath;
this.$refs.localUploadRef.clearFiles();
}else{
this.$Message.error(response.message);
this.local.log.status=response.code;
this.local.log.message=response.message;
}
},
// thượng truyền sau khi thất bại, quét sạch data file, cũng sửa chữa thượng truyền trạng thái
handleLocalError(){
this.local.file=null;
this.local.loadingStatus=false;
this.$Message.error(' thượng truyền thất bại ');
},
// beforeUpload ở phản hồi false hoặc Promise khi, sẽ đình chỉ tự động thượng truyền, nơi này chúng ta đem lựa chọn tốt văn kiện file bảo tồn ở data, cũng return false
handleYunUpload(file){
this.yun.file=file;
returnfalse;
},
// nơi này là tay động thượng truyền, thông qua $refs thu hoạch đến Upload ví dụ thực tế, sau đó thuyên chuyển tư hữu phương pháp.post(), đem bảo tồn ở data file thượng truyền.
// iView Upload lắp ráp ở thuyên chuyển.post() phương pháp khi, liền sẽ tiếp tục thượng truyền.
yunUpload(){
this.yun.loadingStatus=true;// đánh dấu thượng truyền trạng thái
this.$refs.yunUploadRef.post(this.yun.file);
},
// thượng truyền thành công sau, quét sạch data file, cũng sửa chữa thượng truyền trạng thái
handleYunSuccess(response){
this.yun.file=null;
this.yun.loadingStatus=false;
if(response.code===200){
this.$Message.success(response.message);
this.yun.log.status=response.code;
this.yun.log.message=response.message;
this.yun.log.fileName=response.data.fileName;
this.yun.log.filePath=response.data.filePath;
this.$refs.yunUploadRef.clearFiles();
}else{
this.$Message.error(response.message);
this.yun.log.status=response.code;
this.yun.log.message=response.message;
}
},
// thượng truyền sau khi thất bại, quét sạch data file, cũng sửa chữa thượng truyền trạng thái
handleYunError(){
this.yun.file=null;
this.yun.loadingStatus=false;
this.$Message.error(' thượng truyền thất bại ');
}
}
})
</script>
</body>
</html>

Tham khảo

  1. Spring phía chính phủ hồ sơ:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#howto-multipart-file-upload-configuration
  2. Bảy ngưu vân phía chính phủ hồ sơ:https://developer.qiniu /kodo/sdk/1239/java#5