原生方式实现图片,文件上传,和使用ElmentUI使用Drag方式自动上传图片,手动上传图片,OSS图片上传

原生方式实现图片,文件上传

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>

    <!-- cdn引入ElementUI样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!--cdn引入ElementUI组件必须先引入Vue-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- cdn引入ElementUI组件库 -->
<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">
        // 配置对象 options
        const vm = new Vue({
            // 配置选项(option)
            // element: 指定用vue来管理页面中的哪个标签区域
            el: '#app',  
            data: {
              message:"helloword",

               
           
            },

            methods:{
    


            }
 
        });
    </script>
    
</body>
</html>





自动 上传

1.前端代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	<body>
		<!-- Vue开发环境版本,包含了有帮助的命令行警告 -->
		<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
		<!-- 引入element样式element -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<!-- 引入element组件库 -->
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
		<!-- 引入axios -->
		<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");
                    // console.log(fileList,"fileList");
					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格式!");
                        
						// this.$message.error('上传文件格式只能是 JPG PNG TXT PDF XLS XLSX格式!');
				    }
				    if (!isLt2M) {
                        ELEMENT.Message.error("上传头像图片大小不能超过 2MB!");
				        // this.$message.error('上传头像图片大小不能超过 2MB!');
				    }
				        return (isJPG || isPNG || isPDF || isXLSX || isXLS) && isLt2M;
				},
				//  上传成功调用此方法,可以获取到后端返回的文件名称

			  	handleSucess(response,file,fileList) {
					// alert("上传成功")
			  		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 发起请求在新页面显示返回的内容,也可以使用axios,这样比较简单,效果类似
					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();
//     截取.jpg
        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\

ElementUI图片进行上传讲解

手动上传

  1. el-upload组件里面加上
 ref="doctypeCrfile"
 :auto-upload="false" 
  1. 在确定的这个click事件中加上
var vm = this;
vm.$refs.doctypeCrfile.submit();
在这里插入代码片

直接用这个前端代码就行:

1.直接替换自动上传的前端代码

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title></title>

<body>
	<!-- Vue开发环境版本,包含了有帮助的命令行警告 -->
	<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
	<!-- 引入element样式element -->
	<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
	<!-- 引入element组件库 -->
	<script src="https://unpkg.com/element-ui/lib/index.js"></script>
	<!-- 引入axios -->
	<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");
					// console.log(fileList,"fileList");
					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格式!");

						// this.$message.error('上传文件格式只能是 JPG PNG TXT PDF XLS XLSX格式!');
					}
					if (!isLt2M) {
						ELEMENT.Message.error("上传头像图片大小不能超过 2MB!");
						// this.$message.error('上传头像图片大小不能超过 2MB!');
					}
					return (isJPG || isPNG || isPDF || isXLSX || isXLS) && isLt2M;
				},
				//  上传成功调用此方法,可以获取到后端返回的文件名称

				handleSucess(response, file, fileList) {
					// alert("上传成功")
					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 发起请求在新页面显示返回的内容,也可以使用axios,这样比较简单,效果类似
					window.open(url)
				},
				// 上传测试文件
				uploadConfirm() {
					var vm = this;
					vm.$refs.doctypeCrfile.submit();
				},
			}
		})
	</script>
</body>

</html>




Oss图片上传

地址

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有时间指导毕业设计

觉得写的好的话可以给我打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值