html:
<from method="post" id="form1" enctype="multipart/form-data">
<input type="file" name="file0" id="file0" multiple="multiple" />
<input type="button" οnclick="gosubmit()" id="imgbtn" value="上传" />
</from>
<script>
var CardId = getQueryString("CardId");
function gosubmit() {
var formdata = new FormData();
formdata.append('file0', $('#file0').get(0).files[0]);
$.ajax({
url: 'http://xx/UplodImg',
type: 'post',
contentType: false,
data: formdata,
processData: false,
success: function (data) {
},
error: function (err) {
console.log(err)
}
});
}
</script>
后端 c#
public string UplodImg()
{
string result = string.Empty;
string imgPath = string.Empty;
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files;
// 判断是否有文件
if (fileCollection.Count > 0)
{
// 获取图片文件
HttpPostedFile httpPostedFile = fileCollection[0];
// 文件扩展名
string fileExtension = Path.GetExtension(httpPostedFile.FileName);
// 图片名称
string fileName = Guid.NewGuid().ToString() + fileExtension;
// 图片上传路径
string filePath = uploadPath + fileName;
// 验证图片格式
if (fileExtension.Contains(".jpg")
|| fileExtension.Contains(".png")
|| fileExtension.Contains(".bmp"))
{
// 如果目录不存在则要先创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 保存新的图片文件
while (File.Exists(filePath))
{
fileName = Guid.NewGuid().ToString() + fileExtension;
filePath = uploadPath + fileName;
}
httpPostedFile.SaveAs(filePath);
result = "上传成功_" + fileName;
}
else
{
result = "上传失败_请选择jpg/png/bmp格式的图片";
}
}
else
{
result = "上传失败_请先选择图片!";
}
return result;
}