文件上传:
一个上传文件的功能,上传文件的步骤代码都是差不多的
一开始判断传过来的文件是否为空
然后就是获取它文件类型
自己自定义一个文件名
判断是否存在需要的目录,没有就创建一个出来
再然后就是拼接保存的文件路径了
最后就是保存文件
下面是实例代码
控制器中的方法:
public ActionResult UpEeditorFile(HttpPostedFileBase file)
{
ReturnJsonVo returnJson = new ReturnJsonVo();
try
{
//判断文件是否为空
if (file != null)
{
//获取文件类型
string fileExtension = System.IO.Path.GetExtension(file.FileName);
//自定义文件名(时间+唯一标识符+后缀)
string fileName = DateTime.Now.ToString("yyyy-MM-dd") + Guid.NewGuid() + fileExtension;
//判断是否存在需要的目录,不存在则创建
if (!Directory.Exists(Server.MapPath("~/Document/Title/Temp")))
{
Directory.CreateDirectory(Server.MapPath("~/Document/Title/Temp"));
}
if (!Directory.Exists(Server.MapPath("~/Document/Title/Images")))
{
Directory.CreateDirectory(Server.MapPath("~/Document/Title/Images"));
}
//拼接保存文件的详细路径
string filePath = Server.MapPath("~/Document/Title/Temp/") + fileName;
#region 若扩展名不为空则判断文件是否是指定图片类型 ,然后返回img
if (fileExtension != null)
{
//将文件的后缀转化成小写
fileExtension = fileExtension.ToLower();
if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileExtension))
{
//保存文件
file.SaveAs(filePath);
//拼接返回的Img标签
string str = "<img onload=\"AutoResizeImage(200,150,this)\" src=\"/Document/Title/Temp/"+ fileName + "\" />";
returnJson.State = true;
returnJson.Text = str;
}
else
{
returnJson.State = false;
returnJson.Text = "只支持上传图片文件(gif,jpg,bmp,jpeg,png)";
}
}
#endregion
}
else
{
returnJson.State = false;
returnJson.Text = "文件为空";
}
}
catch (Exception)
{
returnJson.State = false;
returnJson.Text = "数据异常!";
}
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
页面前端代码
在html中写一个文件型的input输入框
<form id="formEditorFile" action="UpEeditorFile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" class="form-control" onchange="UpEeditorFile()" />
</form>
一个点击事件把在页面中获取的值传到控制器(也就是文件路径)
function UpEeditorFile() {
//提交表单
$("#formEditorFile").ajaxSubmit(function (data) {
if (data.State) {
//获取内容框中已有的内容
var str = $("#textContent").html();
//将上传的图片拼接到已输入的内容后面
str += data.Text;
//更新内容框
$("#textContent").html(str);
} else {
layer.msg(data.Text, { icon: 0, skin: "layui-layer-molv" });
}
});
}
//1.7图片压缩,在上传上去的图片进行压缩变小,避免上传的图片过大
function AutoResizeImage(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) {//
if (hRatio < 1) Ratio = hRatio;
} else if (maxHeight == 0) {
if (wRatio < 1) Ratio = wRatio;
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}