前端:
[HTML] 纯文本查看 复制代码 <form runat="server" id="form1" method="post" enctype="multipart/form-data"> <label>物流快照:</label>
<input type="file" id="upload" name="upload" accept="image/*" />
<div id="photo"></div>
<input type="hidden" value="" id="hideimg" />
</form>
引入两个js文件
jquery.min.js和jquery-form.js
[JavaScript] 纯文本查看 复制代码 $('#upload').change(function () {
var file = this.files[0];
var r = new FileReader();
r.readAsDataURL(file);
$(r).load(function () {
$("#form1").ajaxSubmit({
success: function (str) {
var data = JSON.parse(str);
if (data.msg != "") {
$('#photo').html('<img src="' + data.filenewname + '" alt="" />');
$("#hideimg").val(data.filenewname);
} else {
layer.open({ content: '上传失败!', skin: 'msg', time: 3 });
}
},
error: function (error) { alert(error); },
url: 'UploadImage.ashx', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "text" /*设置返回值类型为文本*/
});
});
});
后台代码,用的一般处理程序
[C#] 纯文本查看 复制代码
string msg = string.Empty;
string error = string.Empty;
string result = string.Empty;
string filePath = string.Empty;
string fileNewName = string.Empty;
string filename=string.Empty;
//这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
BLL.bll_Setting setting = new BLL.bll_Setting();
DataTable dt = setting.SelectSetting("8");
string uri = dt.Rows[0]["FValue"].ToString();
string thechar=uri.Substring(uri.Length-1,1);
if (thechar=="/")
{
uri = uri.Remove(uri.Length - 1, 1);
}
fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssfff") +"."+ System.IO.Path.GetFileName(files[0].FileName).Split('.')[1];
filename=fileNewName.Substring(0,8);
//保存文件
string dir = context.Server.MapPath("~/upload/"+filename);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
files[0].SaveAs(context.Server.MapPath("~/upload/"+filename+"/" + fileNewName));
string relativeFileFullPath = context.Server.MapPath("~/upload/" + filename + "/" + fileNewName);
string data = UploadFile.Upload_Request(uri + "/SaveForm.aspx?action=seorder", relativeFileFullPath, fileNewName);
string imgurl = uri + "/SEOrderImages/" + filename + "/" + fileNewName;
msg = "文件上传成功!";
result = "{\"msg\":\"" + msg + "\",\"filenewname\":\"" + imgurl + "\"}";
}
else
{
error = "文件上传失败!";
result = "{\"error\":\"" + error + "\"}";
}
context.Response.Write(result);
context.Response.End();
UploadFile.cs
[C#] 纯文本查看 复制代码
/// <summary>
/// 将本地文件上传到指定的服务器(HttpWebRequest方法)
/// </summary>
/// <param name="address">文件上传到的服务器</param>
/// <param name="fileNamePath">要上传的本地文件(全路径)</param>
/// <param name="saveName">文件上传后的名称</param>
/// <returns>成功返回Success,失败返回Error</returns>
public static string Upload_Request(string address, string fileNamePath, string saveName)
{
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //请求头部信息
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
httpReq.Method = "POST"; //对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false; //设置获得响应的超时时间(300秒)
httpReq.Timeout = 300000;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
string returnValue = "";
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs); //时间戳
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(saveName);
sb.Append("\";");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); // 根据uri创建HttpWebRequest对象
long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fs.Length;
httpReq.ContentLength = length;
try
{
int bufferLength = 1024;
byte[] buffer = new byte[bufferLength]; //已上传的字节数
long offset = 0; //开始上传时间
DateTime startTime = DateTime.Now;
int size = r.Read(buffer, 0, bufferLength);
Stream postStream = httpReq.GetRequestStream(); //发送请求头部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
//progressBar.Position = 0;
while (size > 0)
{
postStream.Write(buffer, 0, size);
offset += size;
//Application.DoEvents();
size = r.Read(buffer, 0, bufferLength);
}
//添加尾部的时间戳
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close(); //获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
//读取服务器端返回的消息
StreamReader sr = new StreamReader(s);
String sReturnString = sr.ReadLine();
s.Close();
sr.Close();
returnValue = sReturnString;
}
catch (Exception ex)
{
returnValue = ex.ToString();
}
finally
{
fs.Close();
r.Close();
}
return returnValue;
服务器
[C#] 纯文本查看 复制代码
string action = Request.QueryString["action"];
if (Request.Files.Count > 0)
{
try
{
//获取根目录路径
string M_Path = Server.MapPath("~/");
HttpPostedFile file = Request.Files[0];
string time = file.FileName.Substring(0, 8);
string filePath = "";
if (action == "icitem")
{
if (Directory.Exists(M_Path+"ICItemImages/" + time) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(M_Path + "ICItemImages/" + time);
}
filePath = M_Path + "ICItemImages/" + time + "/" + file.FileName;
}
if (action == "seorder")
{
if (Directory.Exists(M_Path + "SEOrderImages/" + time) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(M_Path + "SEOrderImages/" + time);
}
filePath = M_Path + "SEOrderImages/" + time + "/" + file.FileName;
}
file.SaveAs(filePath);
Response.Write("Success");
}
catch (Exception ex)
{
Response.Write(ex);
}
}
else
{
Response.Write("Error");
}
|