asp.net使用百度的webuploader批量上傳圖片
阿新 • • 發佈:2019-01-06
各位想必是在百度下載webuploader後,看官方的demo並沒有看明白才搜到這裡來的吧。
我也是,我將搜尋的結果做了整理,大家互相學習進步。
下載下來的是一個php的寫的,asp.net的伺服器端得自己重新寫一個服務,將下載的程式碼進行如下修改(這裡使用的是demo中的examples/image-upload/upload.js):
找到154行,將圖片上傳地址修改為.net的一般處理程式的請求地址
server: '../../server/fileupload.php',
修改為您的一般處理程式地址
server: '../../server/fileupload.ashx',
好了,到這裡我們將upload.js修改完成了,如果你要使用到自己的專案中,還需要修改
首先,找到109行的程式碼
var swf = './expressInstall.swf';
修改為您的flash地址:
var swf = '../image/expressInstall.swf';
其次,找到151行,在例項化的時候修改用於上傳flash的地址:
swf: '../../dist/Uploader.swf',
修改為您的
swf: '../image/Uploader.swf',
最後,如果你有自己的預覽的伺服器,還需要修改程式碼地址(我沒有寫不影響檔案上傳)
$.ajax('../../server/preview.php', {
修改為您的一般處理程式的預覽地址
$.ajax('./server/preview.ashx', {
下面就是寫了處理程式了,在專案中server資料夾新增以下兩個檔案fileupload.ashx和preview.ashx。
下面主要介紹fileupload.ashx的實現方法
如有需求,需要修改一下上傳位置和上傳檔案儲存檔名等個人設定。using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Text; namespace FileUpload.server { /// <summary> /// Summary description for fileupload /// </summary> public class fileupload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //指定字符集 context.Response.ContentEncoding = Encoding.UTF8; if (context.Request["REQUEST_METHOD"] == "OPTIONS") { context.Response.End(); } SaveFile(); } /// <summary> /// 檔案儲存操作 /// </summary> /// <param name="basePath"></param> private void SaveFile(string basePath = "~/Upload/Images/") { var name = string.Empty; basePath = (basePath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(basePath) : basePath; HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; //如果目錄不存在,則建立目錄 if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } var suffix = files[0].ContentType.Split('/'); //獲取檔案格式 var _suffix = suffix[1].Equals("jpeg",StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1]; var _temp = System.Web.HttpContext.Current.Request["name"]; //如果不修改檔名,則建立隨機檔名 if (!string.IsNullOrEmpty(_temp)) { name = _temp; } else { Random rand = new Random(24 * (int)DateTime.Now.Ticks); name = rand.Next() + "." + _suffix; } //檔案儲存 var full = basePath + name; files[0].SaveAs(full); var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"" + name + "\"}"; System.Web.HttpContext.Current.Response.Write(_result); } public bool IsReusable { get { return false; } } } }
如有問題,請留言交流。
tip:
private void SaveFile(string basePath = "~/Upload/Images/")
這句程式碼應該只有.net4.0才支援。