原生方式实现图片,文件上传
1.前端代码(后端在下面,可以共用):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片显示并上传</title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<form action="http://localhost:8081/upload1/uploadFile1" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">提交</button>
</form>
</div>
<script type="text/javascript">
const vm = new Vue({
el: '#app',
data: {
message:"helloword",
},
methods:{
}
});
</script>
</body>
</html>
自动 上传
1.前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
{{message}}
<h2>文件上传</h2>
<el-upload
class="upload-demo"
drag
action="http://localhost:8081/upload1/uploadFile1"
multiple
:file-list="fileList"
:on-change="onChange"
:on-success="handleSucess"
:show-file-list = "true"
:before-upload="beforeAvatarUpload">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<img v-if="imageUrl" :src="imageUrl" class="avatar"/>
</el-upload>
<h2>文件下载</h2>
<p>模拟下载,假设下面是某个文件列表</p>
<div @click="downFile"><i class="el-icon-document"></i>娱乐圈不为人知的秘密.pdf</div>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
fileList: [],
fileinfo:{
virtualPath: ""
},
message:"hello",
imageUrl:"",
}
},
methods: {
onChange(file,fileList){
console.log("onChange执行");
console.log(file)
this.fileList = fileList;
console.log(fileList,"fileList")
},
beforeAvatarUpload(file) {
console.log(file,"file");
alert(file.type)
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isPDF = file.type === 'application/pdf';
const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const isXLS = file.type === 'application/vnd.ms-excel'
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG && !isPNG && !isPDF && isXLSX && isXLS) {
ELEMENT.Message.error("上传文件格式只能是 JPG PNG TXT PDF XLS XLSX格式!");
}
if (!isLt2M) {
ELEMENT.Message.error("上传头像图片大小不能超过 2MB!");
}
return (isJPG || isPNG || isPDF || isXLSX || isXLS) && isLt2M;
},
handleSucess(response,file,fileList) {
console.log("存储路径:"+response.virtualPath)
console.log("文件名:"+response.fileName)
alert(response.fileName)
this.fileinfo.virtualPath=response.virtualPath;
this.imageUrl = `http:/localhost:8081/upload/downloadFile1?name=${response.data}`
},
downFile(){
alert("开始下载")
console.log(this.fileinfo.virtualPath)
var url = "http://localhost:8080/downloadFile?filePath="+this.fileinfo.virtualPath
window.open(url)
}
}
})
</script>
</body>
</html>
后端代码
1. controller层
package com.qfedu.fmmall.controller;
import com.qfedu.fmmall.service.UploadService1;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
@RestController
@CrossOrigin
@RequestMapping("/upload1")
public class UploadController1 {
@Resource
private UploadService1 uploadService1;
@PostMapping("/uploadFile1")
public String uploadFile(MultipartFile file) throws IOException {
return uploadService1.uploadFile(file);
}
}
2. service层
package com.qfedu.fmmall.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface UploadService1 {
public String uploadFile(MultipartFile file) throws IOException;
}
3. serviceimpl
package com.qfedu.fmmall.service.impl;
import com.qfedu.fmmall.service.UploadService1;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Service
public class UploadService1impl implements UploadService1 {
@Value("${img.path}")
private String localPath;
@Override
public String uploadFile(MultipartFile file) throws IOException {
System.out.println("file=" + file);
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String name = UUID.randomUUID().toString().substring(1, 8);
File file1 = new File(localPath);
System.out.println("localPath="+localPath);
if(!file1.exists()){
file1.mkdirs();
}
file.transferTo(new File(localPath+name+suffix));
return name+suffix;
}
}
4. yml文件进行配置相关路径
注意一下路径后面需要加上 \ ,需要有空格
img:
path: D:\img\img2\
手动上传
- el-upload组件里面加上
ref="doctypeCrfile"
:auto-upload="false"
- 在确定的这个click事件中加上
var vm = this;
vm.$refs.doctypeCrfile.submit();
在这里插入代码片
直接用这个前端代码就行:
1.直接替换自动上传的前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<el-form>
<el-form-item>
<el-upload
ref="doctypeCrfile" class="upload-demo"
drag
action="http://localhost:8081/upload1/uploadFile1"
multiple
:file-list="fileList"
:on-change="onChange"
:on-success="handleSucess"
:auto-upload="false" :show-file-list="true"
:before-upload="beforeAvatarUpload">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
</el-upload>
<h2>文件下载</h2>
<p>模拟下载,假设下面是某个文件列表</p>
<div @click="downFile"><i class="el-icon-document"></i>娱乐圈不为人知的秘密.pdf</div>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button size="mini" type="primary" @click="uploadConfirm">确 定</el-button>
<el-button size="mini" @click="uploadVisible= false">关 闭</el-button>
</span>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
fileList: [],
fileinfo: {
virtualPath: ""
},
message: "hello",
imageUrl: "",
}
},
methods: {
onChange(file, fileList) {
console.log("onChange执行");
console.log(file)
this.fileList = fileList;
console.log(fileList, "fileList")
},
beforeAvatarUpload(file) {
console.log(file, "file");
alert(file.type)
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isPDF = file.type === 'application/pdf';
const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const isXLS = file.type === 'application/vnd.ms-excel'
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG && !isPNG && !isPDF && isXLSX && isXLS) {
ELEMENT.Message.error("上传文件格式只能是 JPG PNG TXT PDF XLS XLSX格式!");
}
if (!isLt2M) {
ELEMENT.Message.error("上传头像图片大小不能超过 2MB!");
}
return (isJPG || isPNG || isPDF || isXLSX || isXLS) && isLt2M;
},
handleSucess(response, file, fileList) {
console.log("存储路径:" + response.virtualPath)
console.log("文件名:" + response)
ELEMENT.Message.success("上传图片成功:名字为:"+response);
this.fileinfo.virtualPath = response.virtualPath;
this.imageUrl = `http:/localhost:8081/upload/downloadFile1?name=${response.data}`
},
downFile() {
alert("开始下载")
console.log(this.fileinfo.virtualPath)
var url = "http://localhost:8080/downloadFile?filePath=" + this.fileinfo.virtualPath
window.open(url)
},
uploadConfirm() {
var vm = this;
vm.$refs.doctypeCrfile.submit();
},
}
})
</script>
</body>
</html>
|