从零开始的VUE项目-08(el-upload做文件上传)
这一篇中我们利用el-upload来做文件上传,效果如下:el_upload组件文档地址:https://element.eleme.cn/#/zh-CN/component/upload1,在数据库的data表里加一个附件字段Attachment2,在api后台文件夹的根目录新建Img文件夹3,Data.cs添加附件字段,变为:using System;using System.Collecti
代码svn地址 (用户名:liu,密码;123)
这一篇中我们利用el-upload来做文件上传,效果如下:
el_upload组件文档地址:https://element.eleme.cn/#/zh-CN/component/upload
1,在数据库的data表里加一个附件字段Attachment
2,在api后台文件夹的根目录新建Img文件夹
3,Data.cs添加附件字段,变为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace API.Models
{
/// <summary>
/// 数据管理数据类
/// </summary>
public class Data
{
/// <summary>
/// id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// X坐标
/// </summary>
public double? X { get; set; }
/// <summary>
/// Y坐标
/// </summary>
public double? Y { get; set; }
/// <summary>
/// 值
/// </summary>
public double? Num { get; set; }
/// <summary>
/// 附件
/// </summary>
public string Note { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Attachment { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? CreateTime { get; set; }
/// <summary>
/// 更新时间
/// </summary>
public DateTime? UpdateTime { get; set; }
}
}
4,因为新增了一个字段,所以DataCoontroller.cs文件要修改一下,就变为了:
using Newtonsoft.Json;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MySql.Data.MySqlClient;
using System.Collections;
using System.Text;
using System.Threading.Tasks;
using API.Models;
using System.Collections.Generic;
using System.Web;
namespace API.Controllers
{
/// <summary>
/// 数据管理
/// </summary>
public class DataController : ApiController
{
/// <summary>
/// 获取数据
/// </summary>
public MessageModel<PageModel<Data>> Get(int page = 1,int intPageSize=10,string key="")
{
string where = "1=1";
try
{
//数据库连接信息
string sqlCconnStr = "server=localhost;port=3306;user=xxx;password=xxx; database=xxx;charset=utf8";
//连接数据库
MySqlConnection sqlCon = new MySqlConnection(sqlCconnStr);
//建立DataSet对象(相当于建立前台的虚拟数据库)
DataSet ds = new DataSet();
//打开连接
sqlCon.Open();
//建立DataAdapter对象
//查询条件
if (!string.IsNullOrEmpty(key))
{
where = where + " " + "and" + " " + "Name like '%" + key + "%'";
}
string sltStr = "select * from Data WHERE "+where+" order by CreateTime desc,UpdateTime desc";//查询的sql语句
MySqlCommand sqlCmd = new MySqlCommand(sltStr, sqlCon);
MySqlDataReader reader = sqlCmd.ExecuteReader();
var jsonData = ToJson(reader);
sqlCon.Close();
var model = new PageModel<Data>();
model.dataCount = jsonData.Count;
model.AllData = jsonData;
model.data = jsonData.Skip(intPageSize * (page - 1)).Take(intPageSize).ToList();
model.PageSize = intPageSize;
model.page = page;
if (model.data.Count == 0)
{
model.pageCount = 0;
}
else
{
model.pageCount = (int)Math.Ceiling(Convert.ToDouble(model.dataCount / model.data.Count));
}
return new MessageModel<PageModel<Data>>()
{
msg = "获取成功",
success = true,
response = model
};
}
catch (Exception ex)
{
return new MessageModel<PageModel<Data>>()
{
msg = "获取失败",
success = false,
};
}
}
/// <summary>
/// DataReader转换为数组数据
/// </summary>
public List<Data> ToJson(MySqlDataReader dataReader)
{
List<Data> list = new List<Data>();
while (dataReader.Read())
{
var model = new Data();
double?NULL = null;
model.Id = dataReader[0].ToString();
model.Name = dataReader[1].ToString() != "" ?dataReader[1].ToString():null;
model.X =dataReader[2].ToString()!=""? Convert.ToDouble(dataReader[2].ToString()):NULL;
model.Y = dataReader[3].ToString() != "" ? Convert.ToDouble(dataReader[3].ToString()) : NULL;
model.Num = dataReader[4].ToString() != "" ? Convert.ToDouble(dataReader[4].ToString()) : NULL;
model.Note = dataReader[5].ToString() != "" ? dataReader[5].ToString() : null;
model.Attachment = dataReader[8].ToString() != "" ? dataReader[8].ToString() : null;
list.Add(model);
}
dataReader.Close();
return list;
}
/// <summary>
/// 根据Id获取数据
/// </summary>
public MessageModel<PageModel<Data>> GetById(string Id="") {
string where = "1=1";
try
{
//数据库连接信息
string sqlCconnStr = "server=localhost;port=3306;user=xxx;password=xxx; database=xxx;;charset=utf8";
//连接数据库
MySqlConnection sqlCon = new MySqlConnection(sqlCconnStr);
//打开连接
sqlCon.Open();
//建立DataAdapter对象
//查询条件
if (!string.IsNullOrEmpty(Id))
{
where = where + " " + "and" + " " + "Id ='" + Id + "'";
}
string sltStr = "select * from Data WHERE " + where;//查询的sql语句
MySqlCommand sqlCmd = new MySqlCommand(sltStr, sqlCon);
MySqlDataReader reader = sqlCmd.ExecuteReader();
var jsonData = ToJson(reader);
sqlCon.Close();
var model = new PageModel<Data>();
model.data = jsonData;
return new MessageModel<PageModel<Data>>()
{
msg = "获取成功",
success = true,
response = model
};
}
catch (Exception ex)
{
return new MessageModel<PageModel<Data>>()
{
msg = "获取失败",
success = false,
};
}
}
/// <summary>
/// 新增数据
/// </summary>
[HttpPost]
public MessageModel<string> Post([FromBody] Data request)
{
;
var data = new MessageModel<string>();
request.Id = Guid.NewGuid().ToString();
request.CreateTime= DateTime.Now;
var X="null";
if (request.X != null) {
X = request.X.ToString();
}
var Y = "null";
if (request.Y != null)
{
Y = request.Y.ToString();
}
var Num = "null";
if (request.Num != null)
{
Num = request.Num.ToString();
}
var Note = "null";
if (request.Note != null)
{
Note = "'" + request.Note + "'";
}
var Attachment = "null";
if (request.Attachment != null)
{
Attachment = "'" + request.Attachment + "'";
}
try
{
//数据库连接信息
string sqlCconnStr = "server=localhost;port=3306;user=xxx;password=xxx; database=xxx;charset=utf8";
//连接数据库
MySqlConnection sqlCon = new MySqlConnection(sqlCconnStr);
//打开连接
sqlCon.Open();
//建立DataAdapter对象
var N = request.Note;
string sltStr = "insert into Data values( '" + request.Id + "','" + request.Name + "'," + X + "," +Y + "," + Num + "," + Note+ ",'" + request.CreateTime + "',"+"null,"+Attachment+")";//新增的sql语句
//byte[] Str = Encoding.UTF8.GetBytes(sltStr);
//sltStr = Encoding.UTF8.GetString(Str);
MySqlCommand sqlCmd = new MySqlCommand(sltStr, sqlCon);
int i = sqlCmd.ExecuteNonQuery();
sqlCon.Close();
if (i > 0)
{
data.success = true;
data.msg = "新增成功";
data.response = request.Id;
}
return data;
}
catch (Exception ex)
{
return new MessageModel<string>()
{
msg = "新增失败",
success = false,
};
}
}
/// <summary>
/// 编辑数据
/// </summary>
[HttpPost]
public MessageModel<string> Put([FromBody] Data request)
{
;
var data = new MessageModel<string>();
request.UpdateTime = DateTime.Now;
var X = "null";
if (request.X != null)
{
X = request.X.ToString();
}
var Y = "null";
if (request.Y != null)
{
Y = request.Y.ToString();
}
var Num = "null";
if (request.Num != null)
{
Num = request.Num.ToString();
}
var Note = "null";
if (request.Note != null)
{
Note ="'"+ request.Note+"'";
}
var Attachment = "null";
if (request.Attachment != null)
{
Attachment = "'" + request.Attachment + "'";
}
try
{
//数据库连接信息
string sqlCconnStr = "server=localhost;port=3306;user=xxx;password=xxx; database=xxx;charset=utf8";
//连接数据库
MySqlConnection sqlCon = new MySqlConnection(sqlCconnStr);
//打开连接
sqlCon.Open();
//建立DataAdapter对象
var N = request.Note;
string sltStr = "update data set Name='"+request.Name+"',X="+X+",Y="+Y+",Num="+Num+",Note="+Note+ ",Attachment = " + Attachment + ",UpdateTime='" + request.UpdateTime + "' where Id='"+request.Id+"'";//编辑的sql语句
MySqlCommand sqlCmd = new MySqlCommand(sltStr, sqlCon);
int i = sqlCmd.ExecuteNonQuery();
sqlCon.Close();
if (i > 0)
{
data.success = true;
data.msg = "更新成功";
data.response = request.Id;
}
return data;
}
catch (Exception ex)
{
return new MessageModel<string>()
{
msg = "更新失败",
success = false,
};
}
}
/// <summary>
/// 根据Id删除数据
/// </summary>
[HttpGet]
public MessageModel<string> DeleteById(string Id="")
{
var data = new MessageModel<string>();
try
{
//数据库连接信息
string sqlCconnStr = "server=localhost;port=3306;user=xxx;password=xxx; database=xxx;charset=utf8";
//连接数据库
MySqlConnection sqlCon = new MySqlConnection(sqlCconnStr);
//打开连接
sqlCon.Open();
//删除多条数据:"delete from tablename where Id in(1,2,3,5)"
string sltStr = "delete from data where Id='" + Id + "'";//删除一条数据的sql语句
MySqlCommand sqlCmd = new MySqlCommand(sltStr, sqlCon);
int i = sqlCmd.ExecuteNonQuery();
sqlCon.Close();
if (i > 0)
{
data.success = true;
data.msg = "删除成功";
data.response = Id;
}
return data;
}
catch (Exception ex)
{
return new MessageModel<string>()
{
msg = "删除失败",
success = false,
};
}
}
[HttpPost]
public string uploadFile(HttpContext context)
{
HttpResponseMessage response = new HttpResponseMessage();
string path1 = context.Request.Path;
response.Content = new StringContent(path1);
// 获取提交的文件
return path1;
}
}
}
5,在Controllers文件夹里新建控制器类ImgController.cs:
这是用来处理文件上传的
using System;
using System.Web.Http;
using API.Models;
using System.Web;
using System.IO;
namespace API.Controllers
{
/// <summary>
/// 图片管理
/// </summary>
public class ImgController : ApiController
{
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
[HttpPost]
public MessageModel<string> PostAttachFiles()
{
string path;
string returnPath;
try
{
HttpRequest request = HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files;
// 判断是否有文件
if (fileCollection.Count > 0)
{
HttpPostedFile httpPostedFile = fileCollection[0];
// 获取文件扩展名
string fileExtension = Path.GetExtension(httpPostedFile.FileName);
string strHashData = DateTime.Now.ToString("yyyyMMddHHmmssffff");
System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Img\\" + strHashData);
// 设置上传路径
path = AppDomain.CurrentDomain.BaseDirectory + "Img\\" + strHashData+ "\\"+httpPostedFile.FileName;
returnPath= "Img\\" + strHashData + "\\" + httpPostedFile.FileName;
httpPostedFile.SaveAs(path);
}
else
{
return new MessageModel<string>()
{
msg = "上传失败",
success = false,
};
}
}
catch(Exception ex) {
return new MessageModel<string>()
{
msg = "上传失败",
success = false,
};
}
return new MessageModel<string>()
{
msg = "上传成功",
success = true,
response = returnPath
};
}
}
}
6,好的,后台搞好了,让我们回到前端。
先在api.js里把附件上传的接口写好:
// 附件上传
export const uploadFile=params=> {
return axios.post(`${base}/api/Img/PostAttachFiles`,params,{headers:{"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"}})
}
7,然后打开Add.vue,在
<el-form-item label="数值"
prop="Num">
<el-input v-model="addForm.Num"
type="number"
step="0.001"
maxlength="11"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
后面加上:
<el-form-item label="附件">
<el-upload ref="upload"
action=""
list-type="picture"
accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
:file-list="fileList"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:on-change="handleChange"
:on-success="uploadSuccess"
:auto-upload="false"
:http-request="uploadFile"
:on-error="error"
:before-upload="beforeUpload">
<el-button slot="trigger"
size="small"
type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;"
size="small"
type="success"
@click="submitUpload">上传到服务器</el-button>
</el-upload>
</el-form-item>
这里的accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
表示只允许上传图片格式的文件,如果还想上传其它格式的文件直接把允许的格式名加进来就可以,例如: accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP,.xls,.xlsx,.doc,.docx,.pdf,.txt"
,但这样的话预览图片哪里就需要作判断了,如果是图片格式就可以预览,如果是其它文件格式就不可以预览,只显示文件名。
引入上传文件的方法:
import { addData, uploadFile } from '../../api/api'
在methods写需要的方法:
// 移除附件
handleRemove (file, fileList) {
this.fileList=[]
this.$message({
type:"success",
message:"移除附件成功"
})
},
//禁止删除
beforeRemove () {
return false
},
// 超过限制数量
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
// 上传前
beforeUpload (file) {
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
// 限制上传格式为图片
// const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png';
const extension = testmsg === 'xls' || 'xlsx'
const isLt2M = file.size / 1024 / 1024 < 10 //这里做文件大小限制
if (!extension) {
this.$message({
message: '上传文件只能是 xls、xlsx格式!',
type: 'warning'
});
}
if (!isLt2M) {
this.$message({
message: '上传文件大小不能超过 10MB!',
type: 'warning'
});
}
return extension && isLt2M
},
//上传成功
uploadSuccess (response, file, fileList) {
if (response.code == 200) {
//状态码为200时则上传成功
} else {
//状态码不是200时上传失败 从列表中删除
fileList.splice(fileList.indexOf(file), 1);
}
},
//手动上传
submitUpload () {
this.$refs.upload.submit();
},
//上传文件处理
handleChange (file, fileList) {
if (fileList.length > 0) {
this.fileList=[fileList[fileList.length - 1]]// 这一步,是 展示最后一次选择的文件
}
},
//上传到服务器
uploadFile (params) {
const form = new FormData()
form.append('file', params.file,params.file.name)
uploadFile(form).then(response => {
if (response.data.success) {
this.$message({
message: response.data.msg,
type: 'success',
})
this.addForm.Attachment=response.data.response.replace(/\\/g,"\\\\")
}
else {
this.$message({
message: response.data.msg,
type: 'error',
})
}
})
},
//上传失败
error (response, file, fileList) {
console.log('上传失败')
},
点击选取文件,显示图片缩略图;点击上传到服务器,图片就上传到了之前创建Img文件夹里。
Add.vue全部代码:
<!--数据管理-新增-->
<template>
<section style="overflow: hidden; height: 100%;">
<el-form label-width="80px"
ref="addForm"
:model="addForm"
class="form-box"
size="mini">
<el-form-item label="名称"
prop="Name">
<el-input v-model="addForm.Name"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
<el-form-item label="X坐标"
prop="X">
<el-input v-model="addForm.X"
type="number"
step="0.001"
maxlength="11"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
<el-form-item label="Y坐标"
prop="Y">
<el-input v-model="addForm.Y"
type="number"
step="0.001"
maxlength="11"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
<el-form-item style="text-align:right">
<el-button size="mini"
type="primary"
@click.native="pick">拾取坐标</el-button>
</el-form-item>
<el-form-item label="数值"
prop="Num">
<el-input v-model="addForm.Num"
type="number"
step="0.001"
maxlength="11"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
<el-form-item label="附件">
<el-upload ref="upload"
action=""
list-type="picture"
accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
:file-list="fileList"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:on-change="handleChange"
:on-success="uploadSuccess"
:auto-upload="false"
:http-request="uploadFile"
:on-error="error"
:before-upload="beforeUpload">
<el-button slot="trigger"
size="small"
type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;"
size="small"
type="success"
@click="submitUpload">上传到服务器</el-button>
</el-upload>
</el-form-item>
<el-form-item label="备注"
prop="Note">
<el-input v-model="addForm.Note"
auto-complete="off"
size="mini"></el-input>
</el-form-item>
</el-form>
<el-col :span="24"
style="text-align:right">
<el-button size="mini"
@click.native="handleCancelForm">取消</el-button>
<el-button size="mini"
type="primary"
@click.native="addSubmit"
:loading="submitloading">提交</el-button>
</el-col>
</section>
</template>
<script>
import helper from '../../components/layer/helper/helper'
import { addData, uploadFile } from '../../api/api'
import { strRebuild, lastSubstring } from '../../../util/strUtil'
import { message } from '../../../util/message'
export default {
data () {
return {
layerid_p: this.info.layerid_p, //父弹窗id
layerid_c: this.layerid, //弹窗id
submitloading: false, //提交状态
addForm: {
Name: '',
X: '',
Y: '',
Num: '',
Note: '',
Attachment:''
},
// 附件列表
fileList: [],
// 允许的文件类型
fileType: ['xls', 'xlsx', 'pdf', 'doc', 'docx', 'txt', 'jpg', 'png', 'jpeg'],
// 运行上传文件大小,单位 M
fileSize: 10,
}
},
props: {
info: {
type: Object,
default: () => {
return {}
},
},
layerid: {
type: String,
default: '',
},
lyoption: {
type: Object,
default: () => {
return {}
},
},
},
methods: {
//新增取消
handleCancelForm () {
this.$layer.close(this.layerid_c);
},
//新增提交
addSubmit () {
this.submitloading = true
let form = Object.assign({}, this.addForm)
//提交的数据至少有一个名称值
if (form.Name == null || form.Name == '') {
this.$message({
message: "名称不能为空",
type: 'warning',
})
this.submitloading = false
return
}
addData(form).then((res) => {
if (res.data.success) {
this.$message({
message: res.data.msg,
type: 'success',
})
//刷新表格
helper.btnyes(null, this.lyoption)
//关闭弹窗
this.$layer.close(this.layerid_c)
}
else {
this.$message({
message: res.data.msg,
type: 'error',
})
}
}).catch((e) => {
this.$message({
message: e.message,
type: 'error',
})
}).finally(() => {
this.submitloading = false
})
},
//拾取坐标
pick () {
let that = this
//最小化弹窗
this.$layer.min(that.layerid_p)
this.$layer.min(that.layerid_c)
var map = window.map
function pickcallback (event) {
that.addForm.X = parseFloat(event.mapPoint.x).toFixed(3)
that.addForm.Y = parseFloat(event.mapPoint.y).toFixed(3)
that.$layer.restore(that.layerid_p)
that.$layer.restore(that.layerid_c)
//这里一定要解绑事件,不然多个弹窗同时操作的时候弹窗的id会只认识第一次绑定时的id,导致无法进行多个弹窗同时操作
bindClick && bindClick.remove()
}
var bindClick = map.on('click', function (event) {
pickcallback(event)
})
},
// 移除附件
handleRemove (file, fileList) {
this.fileList=[]
this.$message({
type:"success",
message:"移除附件成功"
})
},
//禁止删除
beforeRemove () {
return false
},
// 超过限制数量
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
// 上传前
beforeUpload (file) {
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
// 限制上传格式为图片
// const isIMAGE = file.type === 'image/jpeg'||'image/gif'||'image/png';
const extension = testmsg === 'xls' || 'xlsx'
const isLt2M = file.size / 1024 / 1024 < 10 //这里做文件大小限制
if (!extension) {
this.$message({
message: '上传文件只能是 xls、xlsx格式!',
type: 'warning'
});
}
if (!isLt2M) {
this.$message({
message: '上传文件大小不能超过 10MB!',
type: 'warning'
});
}
return extension && isLt2M
},
//上传成功
uploadSuccess (response, file, fileList) {
if (response.code == 200) {
//状态码为200时则上传成功
} else {
//状态码不是200时上传失败 从列表中删除
fileList.splice(fileList.indexOf(file), 1);
}
},
//手动上传
submitUpload () {
this.$refs.upload.submit();
},
//上传文件处理
handleChange (file, fileList) {
if (fileList.length > 0) {
this.fileList=[fileList[fileList.length - 1]]// 这一步,是 展示最后一次选择的文件
}
},
//上传到服务器
uploadFile (params) {
const form = new FormData()
form.append('file', params.file,params.file.name)
uploadFile(form).then(response => {
if (response.data.success) {
this.$message({
message: response.data.msg,
type: 'success',
})
this.addForm.Attachment=response.data.response.replace(/\\/g,"\\\\")
}
else {
this.$message({
message: response.data.msg,
type: 'error',
})
}
})
},
//上传失败
error (response, file, fileList) {
console.log('上传失败')
},
},
mounted () {
}
}
</script>
<style scoped>
.form-box {
margin-top: 10%;
}
</style>
编辑和详情里显示图片就不赘述了,通过fileList就行了(这里通过IIS发布了Project文件夹,因为不能直接访问本地文件,IIS发布前面有)
if (this.editForm.Attachment) {
var index = this.editForm.Attachment.lastIndexOf("\\");
let name_p = this.editForm.Attachment.substring(index + 1, this.editForm.Attachment.length);
this.fileList.push({
name: name_p,
url: "http://localhost:8083/API/API/" + this.editForm.Attachment
})
}
更多推荐
所有评论(0)