.vue文件,指定文件上傳的接口地址
<el-form-item label="封面圖片">
<el-input v-model="facepicUrlShow"></el-input>
<el-upload
class="upload-facepic"
action="xxxxxxx"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
ref="upload"
:auto-upload="true"
:limit="1"
:on-change="handleChange"
:on-success="handleSuccess"
:on-exceed="handleExceed"
:file-list="fileList"
:data="form">
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/jpeg/png文件,且不超過500kb</div>
</el-upload>
</el-form-item>
這裏選擇圖片後自動上傳
這裏通過element-ui的回調函數在input框中返回圖片名稱,這個只是爲了好看一點,不加也無所謂
handleChange:function (file, fileList) {
this.facepicUrlShow = file.name;
},
後端springboot添加依賴,我這裏用的是commons.io
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
後端springboot中controller層,上傳文件是使用MultipartFile類
@RequestMapping(value = "/uploadfile")
public CommonResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
// 文件名
String fileName = file.getOriginalFilename();
// 在file文件夾中創建名爲fileName的文件
assert fileName != null;
int split = fileName.lastIndexOf(".");
// 文件後綴,用於判斷上傳的文件是否是合法的
String suffix = fileName.substring(split+1,fileName.length());
//判斷文件類型,因爲我這邊是圖片,所以只設置三種合法格式
String url = "";
if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)) {
// 正確的類型,保存文件
try {
File path = new File(ResourceUtils.getURL("classpath:").getPath());
File upload = new File(path.getAbsolutePath(), "upload/");
if(!upload.exists()) {
upload.mkdirs();
}
String newName = System.currentTimeMillis() + "."+suffix;
String homepath = "/home/upload/images";
File savedFile = new File(upload + "/" + newName);
file.transferTo(savedFile);
url = savedFile.getAbsolutePath();
System.out.println("圖片上傳完畢,存儲地址爲:"+ url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
//錯誤的類型,返回錯誤提示
}
File savedFile;
return CommonResult.success(url);
}
這裏我踩坑費了好大勁,網上上傳文件的代碼本地都沒有問題,一旦打成jar包,在Linux服務器上運行,就會找不到文件路徑
有兩種辦法
第一種,自己定義一個服務器上的絕對路徑,我這裏定義了homepath,是服務器上某個文件夾的地址,把xxxxx換成你定義的上傳路徑
File savedFile = new File("xxxxx" + newName);
第二種,使用相對路徑,就是代碼裏寫的,在application.properties文件中加上
默認情況下,會映射資源/**
但你可以通過spring.mvc.static-path-pattern
調整該資源
#這表示只有靜態資源的訪問路徑爲/resources/**時,纔會處理請求
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:upload/
表示靜態資源的訪問路徑,我這裏就放在resources/upload下面,此時本地上傳文件路徑就是項目/target/classes/upload
圖片上傳完畢,存儲地址爲:/Users/Arithmetic/yunprophet/target/classes/upload/1584874173552.png
如果是服務器端,路徑就是