NET Core图片上传
前端
下面展示一些 内联代码片
。
<div class="col-md-8">
<input type="text" id="updateFile" name="fileName" class="form-control batch-upload-text" placeholder="请选择图片文件" />
</div>
<div class="col-md-2">
<input type="button" class="btn btn-primary" value="浏览" onclick="javascript:$('input[name=\'file\']').click();" />
<input type="file" name="file" style="display: none;" onchange="javascript:$('input[name=\'fileName\']').val(this.files[0].name);" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" mulpitle />
<button type="submit" name="save" class="btn bg-blue">
<i class="fa fa-floppy-o"></i>
保存
</button>
</div>
后端
public imagurl ToImage(IFormFile files)
{
var da = new imagurl();
if (files==null)
{
da.fiag = false;
}
//返回的文件地址
List<string> filenames = new List<string>();
var now = DateTime.Now;
//文件存储路径
var filePath = string.Format("wwwroot/images/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("MM"), now.ToString("dd"));
//获取当前web目录
//var webRootPath = _hostingEnvironment.WebRootPath;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory( filePath);
}
try
{
if (files != null)
{
#region 图片文件的条件判断
//判断文件大小
long length = files.Length;
//if (length > 1024 * 1024 * 2) //2M
//{
// return false;
// //return Error("上传的文件不能大于2M");
//}
#endregion
var strDateTime = DateTime.Now.ToString("hhmmssfff"); //取得时间字符串
var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
var saveName = strDateTime + strRan ;
//插入图片数据
using (FileStream fs = System.IO.File.Create( filePath + saveName))
{
files.CopyTo(fs);
fs.Flush();
}
filenames.Add(filePath + saveName);
da.fiag = true;
da.url = filePath + saveName;
}
return da;
}
catch (Exception ex)
{
//这边增加日志,记录错误的原因
//ex.ToString();
da.fiag = false;
return da;
}
}