Encountered a tricky problem. I have been using form submission to upload files before, but this time I need to upload the file without refreshing, and return a path to the input to upload to the database and save it. Single file and multiple files are fine. I only upload pictures, other types can be modified.
It's not a new technology anymore, it's implemented with Formdata.
During the period, I wanted to use the separate upload function of the Baidu Ueditor editor, but after studying it for a while, it is not so easy to use, and it is uncontrollable to use a third party. Maybe the next version will remove some functions. After searching, I finally solved it, and posted the code for everyone to learn from: I use asp.net as the background, and the background language is basically the same
This is the foreground html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Ajax提交form</title>
<script type="text/javascript">
function uploadqin(fileAttach,imgurl) {
var formData = new FormData();
// HTML 文件类型input,由用户选择;fileAttach是input type=file控件的id
for (var i = 0; i < fileAttach.files.length; i++) {
formData.append(fileAttach.files[i].name, fileAttach.files[i]);
}
// formData.append("userfile", fileAttach.files[0]);//左边的是单个文件上传,需要去掉input的multiple属性
// JavaScript file-like 对象
var request = new XMLHttpRequest();
request.open("POST", "upload.ashx");
request.send(formData);
request.onreadystatechange = () => {//在这里指定上传成功的回调函数,接受返回值
if (request.readyState == 4 && request.status == 200) {
let res = request.responseText;
// console.log(res)
imgurl.value=res;
}
};
}
</script>
</head>
<body>
<input name="imgurl" id="imgurl" type="text" placeholder="请上传图片或输入网络图片地址" style="width:518px;"/>
<input type="file" id="uploadimg" value="上传图片" οnchange="javascript:uploadqin(document.getElementById('uploadimg'),document.getElementById('imgurl'))" />
</body>
</html>
Background receiving code: upload.ashx, the code is very simple to understand, don't be afraid when you see so many, I commented the single file upload.
<%@ WebHandler Language="C#" Class="upload" %>
using System;
using System.Web;
using System.IO;
using System.Collections;
public class upload : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp,ico");
//string type_code = context.Request["userName"];
//string xiangmuid = context.Request["userid"];
try
{
HttpPostedFile file;
file = context.Request.Files[0];
string fileName = file.FileName;
string fileExt = Path.GetExtension(fileName).ToLower();
if (fileExt == "")
{
fileExt = ".jpg";
}
if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) return;
string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;
string year = DateTime.Now.Year.ToString();
string monthday = DateTime.Now.ToString("MMdd");
if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year);
}
if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday);
}
string lujing = "documentimage/" + year + "/" + monthday + "/" + filename;
if (fileExt == ".jpg" || fileExt == ".bmp" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".ico")
{
shangchuan(file, context.Server.MapPath(lujing));
context.Response.Write("../admin/" + lujing);
}
}
catch (Exception ex)
{
//context.Response.StatusCode = 500;
//context.Response.Write(ex.Message);
context.Response.Write("0");
context.Response.End();
}
finally
{
context.Response.End();
}
///下面是多文件上传
/*context.Response.ContentType = "text/plain";
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp,ico");
//string type_code = context.Request["userName"];
//string xiangmuid = context.Request["userid"];
try
{
HttpPostedFile file;
for (int i = 0; i < context.Request.Files.Count; ++i)
{
file = context.Request.Files[i];
string fileName = file.FileName;
string fileExt = Path.GetExtension(fileName).ToLower();
if (fileExt == "")
{
fileExt = ".jpg";
}
if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) continue;
string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;
string year = DateTime.Now.Year.ToString();
string monthday = DateTime.Now.ToString("MMdd");
if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year);
}
if (!Directory.Exists(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("documentimage/") + year + "/" + monthday);
}
string lujing = "documentimage/" + year + "/" + monthday + "/" + filename;
if (fileExt == ".jpg" || fileExt == ".bmp" || fileExt == ".gif" || fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".ico")
{
shangchuan(file, context.Server.MapPath(lujing));
context.Response.Write("sucess——" + lujing);
}
//string zhiyoufilename = Path.GetFileName(file.FileName).Replace(fileExt, "");
//string sql_add = "insert into image(image_name,type_code,image_url,xiangmuid) values('" + zhiyoufilename.Trim() + "',"+type_code+",'" + lujing + "'," + xiangmuid + ")";
//string sql_add = "insert into image(type_code,image_url,xiangmuid) values("+type_code+",'" + lujing + "'," + xiangmuid + ")";
}
}
catch (Exception ex)
{
//context.Response.StatusCode = 500;
//context.Response.Write(ex.Message);
context.Response.Write("0");
context.Response.End();
}
finally
{
context.Response.End();
}*/
}
public bool IsReusable {
get {
return false;
}
}
private void shangchuan(HttpPostedFile imgFile, string lujing)
{
Stream sr = imgFile.InputStream;
System.Drawing.Image originalImage = System.Drawing.Image.FromStream(sr);
int newwidth = 0;
int newheight = 0;
caijian(originalImage, 800, 600, ref newwidth, ref newheight);
System.Drawing.Image bitmap = new System.Drawing.Bitmap(originalImage, newwidth, newheight);
bitmap.Save(lujing, System.Drawing.Imaging.ImageFormat.Jpeg);
sr.Close();
bitmap.Dispose();
originalImage.Dispose();
}
private void caijian(System.Drawing.Image ASrcImg, int AWidth, int AHeight, ref int nwidth, ref int nheight)
{
double ADestRate = ASrcImg.Width * 1.0 / ASrcImg.Height;
if (ASrcImg.Width >= ASrcImg.Height)
{
if (ASrcImg.Width >= AWidth)
{
nwidth = AWidth;
nheight = (int)(AWidth / ADestRate);
}
else
{
nwidth = ASrcImg.Width;
nheight = (int)(ASrcImg.Width / ADestRate);
}
}
else
{
if (ASrcImg.Height >= AHeight)
{
nheight = AHeight;
nwidth = (int)(AHeight * ADestRate);
}
else
{
nheight = ASrcImg.Height;
nwidth = (int)(ASrcImg.Height * ADestRate);
}
}
}
}