package lesson.com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);// 這兩句不加不能跨域上傳檔案,
corsConfiguration.setMaxAge(3600l);// 加上去就可以了
return corsConfiguration;
}
/**
* 跨域過濾器
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
package lesson.com;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@CrossOrigin
public class FileUploadController {
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
System.out.println(System.getProperty("user.dir"));
String path = System.getProperty("user.dir") + File.separator + "images";
createDir(path);
if (!file.isEmpty()) {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(
new File(path + File.separator + System.currentTimeMillis() + file.getOriginalFilename())));
System.out.println(file.getName());
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上傳失敗," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上傳失敗," + e.getMessage();
}
return "上傳成功";
} else {
return "上傳失敗,因為檔案是空的.";
}
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("建立目錄" + destDirName + "失敗,目标目錄已經存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 建立目錄
if (dir.mkdirs()) {
System.out.println("建立目錄" + destDirName + "成功!");
return true;
} else {
System.out.println("建立目錄" + destDirName + "失敗!");
return false;
}
}
}
<template>
<!--
<div class="layout">
<Layout>
<Header>
<Menu mode="horizontal" theme="dark" active-name="1">
<div class="layout-logo">
測試系統
</div>
<div class="layout-nav">
<MenuItem name="1">
<Icon type="ios-navigate"></Icon>
<router-link to="/RouteInfo">Go to Foo</router-link>
</MenuItem>
</div>
</Menu>
</Header>
<Layout>
<Sider hide-trigger :style="{background: '#fff'}">
<Menu active-name="1-2" theme="light" width="auto" :open-names="['1']" :style="{minHeight: '824px',}">
<Submenu name="1">
<template slot="title">
<Icon type="ios-navigate"></Icon>
項目資訊
</template>
<MenuItem name="1-1"><router-link to="/RouteInfo">Go to Foo</router-link></MenuItem>
<MenuItem name="1-2"><router-link to="/projectone">項目一</router-link></MenuItem>
<MenuItem name="1-3"><router-link to="/projecttwo">項目二</router-link></MenuItem>
</Submenu>
<Submenu name="2">
<template slot="title">
<Icon type="ios-keypad"></Icon>
版本資訊
</template>
<MenuItem name="2-1"><router-link to="/versionone">版本一</router-link></MenuItem>
<MenuItem name="2-2"><router-link to="/versiontwo">版本二</router-link></MenuItem>
</Submenu>
</Menu>
</Sider>
<Layout :style="{padding: '0 24px 24px'}">
<Content :style="{padding: '24px', minHeight: '800px', background: '#fff'}">
<router-view></router-view>
</Content>
</Layout>
</Layout>
</Layout>
</div>
-->
<div>
<div id="myUpload">
<el-button type="primary" size="mini" @click="uploadFile">導入</el-button>
<!--上傳-->
<el-dialog title="上傳" width="40%" :visible.sync="uploadTemplateDialog">
<el-row>
<el-col :span="22">
<el-upload
class="upload-demo"
ref="upload"
action
:accept="acceptFileType"
:limit="1"
:on-exceed="handleExceed"
:before-upload="beforeUpload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">選取jpg格式檔案</el-button>
<div slot="tip" class="el-upload_tip">隻能上傳.jpg檔案,且不超過1M</div>
</el-upload>
</el-col>
</el-row>
<span slot="footer" class="dialog-footer">
<el-button @click="submitUpload" type="primary" size="mini" :loading="uploadLoading">确定上傳</el-button>
<el-button @click="uploadTemplateDialog=false" size="mini">取消</el-button>
</span>
</el-dialog>
</div>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import axios from "axios";
export default {
components: {
HelloWorld: HelloWorld
},
data() {
return {
message: "Hello Vue!",
isCollapsed: false,
fileList: [],
uploadTemplateDialog: false,
fileList: [],
uploadLoading: false,
acceptFileType: ".jpg",
downLoadLoading: ""
};
},
created: function() {},
//鈎子函數,頁面加載完成後執行
mounted() {},
//函數方法
methods: {
uploadFile() {
this.uploadLoading = false;
var that = this;
this.fileList = [];
this.uploadTemplateDialog = true;
setTimeout(function() {
that.$refs.upload.clearFiles();
}, 100);
},
handleExceed(files, fileList) {
this.$message.warning("隻能選擇1個檔案!");
},
submitUpload() {
this.uploadLoading = true;
var that = this;
setTimeout(function() {
if (that.$refs.upload.$children[0].fileList.length == 1) {
that.$refs.upload.submit();
} else {
that.uploadLoading = false;
that.$message({
type: "error",
showClose: true,
duration: 3000,
message: "請選擇檔案!"
});
}
}, 100);
},
handleRemove(file, fileList) {
//console.log(file,fileList);
},
handlePreview(file) {
//console.log(file);
},
beforeUpload(file) {
var that = this;
//檔案類型
var fileName = file.name.substring(file.name.lastIndexOf(".") + 1);
if (fileName != "jpg") {
that.uploadTemplateDialog = false;
that.$message({
type: "error",
showClose: true,
duration: 3000,
message: "檔案類型不是.xls檔案!"
});
return false;
}
//讀取檔案大小
var fileSize = file.size;
console.log(fileSize);
if (fileSize > 1048576) {
that.uploadTemplateDialog = false;
that.$message({
type: "error",
showClose: true,
duration: 3000,
message: "檔案大于1M!"
});
return false;
}
that.downloadLoading = that.$loading({
lock: true,
text: "資料導入中...",
spinner: "el-icon-loading",
background: "rgba(0,0,0,0.7)"
});
let fd = new FormData();
fd.append("file", file);
fd.append("_t1", new Date());
axios({
method: "post",
url: "http://localhost:9007/upload/",
data: fd,
headers: {
"Content-Type": "multipart/form-data;boundary=" + new Date().getTime()
}
})
.then(rsp => {
that.downloadLoading.close();
that.uploadLoading = false;
let resp = rsp.data;
if (resp.resultCode == 200) {
that.uploadTemplateDialog = false;
that.$message.success(resp.resultMsg);
//that.queryData();//更新資料
} else {
that.uploadTemplateDialog = false;
that.$message({
type: "error",
showClose: true,
duration: 60000,
message: resp.resultMsg
});
}
})
.catch(error => {
that.downloadLoading.close();
that.uploadLoading = false;
that.uploadTemplateDialog = false;
that.$message({
type: "error",
showClose: true,
duration: 60000,
message: "請求失敗! error:" + error
});
});
return false;
}
}
};
</script>
<style scoped>
.layout {
border: 1px solid #d7dde4;
background: #f5f7f9;
position: relative;
border-radius: 4px;
overflow: hidden;
}
.layout-logo {
width: 100px;
height: 30px;
background: #5b6270;
border-radius: 3px;
float: left;
position: relative;
top: 15px;
left: 20px;
color: #ffffff;
line-height: 30px;
text-align: center;
}
.layout-nav {
width: 420px;
margin: 0 auto;
margin-right: 20px;
}
</style>