前台
html:
<div>
<inputtype="file"onchange="selectImage(this.files)"accept="">
</div>
js:
functionselectImage(files){
letreader=newFileReader();
letfile=files[0];
reader.readAsDataURL(file);
reader.onload=function(){
$.post('/Home/UpLoadFile',{filecontent:reader.result},function(result){
});
}
}
后端
base64转化的工具类:
publicclassBase64Convert
{
///<summary>
///文件转换成Base64字符串
///</summary>
///<paramname="fileName">文件绝对路径</param>
///<returns></returns>
publicstaticStringFileToBase64(stringfileName)
{
stringstrRet=null;
try
{
FileStreamfs=newFileStream(fileName,FileMode.Open);
byte[]bt=newbyte[fs.Length];
fs.Read(bt,0,bt.Length);
strRet=Convert.ToBase64String(bt);
fs.Close();
}
catch(Exceptionex)
{
throwex;
}
returnstrRet;
}
///<summary>
///Base64字符串转换成文件
///</summary>
///<paramname="strInput">base64字符串</param>
///<paramname="fileName">保存文件的绝对路径</param>
///<returns></returns>
publicstaticboolBase64ToFileAndSave(stringstrInput,stringfileName)
{
boolbTrue=false;
try
{
byte[]buffer=Convert.FromBase64String(strInput);
FileStreamfs=newFileStream(fileName,FileMode.CreateNew);
fs.Write(buffer,0,buffer.Length);
fs.Close();
bTrue=true;
}
catch(Exceptionex)
{
throwex;
}
returnbTrue;
}
}
提交的控制器:
publicIActionResultUpLoadFile()
{
stringbase64=Request.Form["filecontent"];
//base64需要把前面的申明去掉
stringnewbase=base64.Replace("data:image/jpeg;base64,","");
//把图片存储到c盘,具体操作的时候位置可以自行改变
Base64Convert.Base64ToFileAndSave(newbase,"c://timg.jpg");
returnView();
}
优化一下
前台的时候把图片后缀名传过去
<script>
functionselectImage(files){
letreader=newFileReader();
letfile=files[0];
console.log(file);
//取出来文件的后缀名(方便在后台保存的时候用)
varindex=file.name.lastIndexOf(".");
varfileExt=file.name.substr(index+1);
console.log(fileExt);
reader.readAsDataURL(file);
reader.onload=function(){
console.log(reader.result);
$.post('/Home/UpLoadFile',{filecontent:reader.result,fileExt:fileExt},function(result){
});
}
}
</script>
后台去掉前缀的方法换成正则表达式,因为格式不固定
///<summary>
///base64图片上传
///</summary>
publicvoidUpLoadFile()
{
stringbase64=Request.Form["filecontent"];
stringfileExt=Request.Form["fileExt"];
#regionbase64需要把前面的申明去掉(当然前缀这个也可以放在前端处理)
//stringnewbase=base64.Replace("data:image/jpeg;base64,","");
//这里用了一下正则表达式因为可能是格式data:image/jpeg;base64,data:image/png;base64等等
stringbase64img=Regex.Replace(base64,"data:image/.*;base64,","");
#endregion
}
保存的时候图片名字用guid
//把图片存储到c盘,具体操作的时候位置可以自行改变
Base64Convert.Base64ToFileAndSave(base64img,"c://"+Guid.NewGuid().ToString().Replace("-","")+"."+fileExt);