文件上傳在系統中是一個很常見的功能,如今將angular文件上傳的代碼總結一下。在此特別感謝同事陳衛兵提供的思路總結。html
一、前端頁面前端
(1)提交的時候用ng-submit進行提交。算法
(2)form表單的enctype屬性改成multipart/form-datajson
(3)增長一個文件上傳的input
c#
<form ng-submit="submitDrgMetaData()" enctype="multipart/form-data"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">新增信息</h4> </div> <div class="modal-body clearfix"> <div class="col-md-4" ng-repeat=" con in Drgaggregate"> <label>{{con.chName}}</label><input type="text" ng-model="DrgObj[con.field]" pattern="({{con.pattern}})" class="{{con.className}}" title="{{con.errorMsg}}"/> </div> <div class="col-md-4"> <label>上傳文件</label> <input type="file" id="Drgfile-to-upload" class="inpbackblue"> </div> </div> <div class="modal-footer "> <button type="submit" class="btn btn-danger">肯定</button> </div> </div> </form>
二、angular中的處理api
(1)在define中要引入fileUpload和angularFileUpload模塊ide
配置paths和shim fileUpload: 'scripts/js/file-upload/angular-file-upload',
define(['angular','./basicData_service', 'fileUpload'], function (angular) { 'use strict'; angular.module('apt.basicData.controllers', ['apt.basicData_service', 'angularFileUpload'])
// 表格數據和文件上傳事件 $scope.submitMetaData = function () { $scope.imgObj.RefId = $scope.id; console.log($scope.imgObj); var $file = document.getElementById('file-to-upload').files[0]; console.info($file); $upload.upload({ url: 'http://localhost:8888/api/ImageMetaData', method: "POST", data: {data: $scope.imgObj}, file: $file }).then(function (response) { $scope.getImgMetaData($scope.id) $('#ImageMetaFrom').modal('hide'); }); }
三、後臺的處理url
(1)後臺中的數據和文件是分別獲取的。
spa
// POST api/tombskeepingstatus public virtual HttpResponseMessage Post() { if (ModelState.IsValid) { if (!Request.Content.IsMimeMultipartContent("form-data")) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); var form = HttpContext.Current.Request.Form["data"]; ImageMetaData image = JsonHelper.DeserializeFromJson<ImageMetaData>(form);//ConvertToModel(form); //獲取表單中的文件 var fileinfo = HttpContext.Current.Request.Files[0]; image.RomotePath = FileLoadHelper.Up(fileinfo); tasks.SaveOrUpdate(image); /* var message = new HttpRequestMessage();*/ /*message.Headers.Add("FileName", result.); message.Headers.Add("Directory", result.Directory);*/ /* return base.Post(value);*/ HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created,image); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
namespace Apt.MWSGR.Domain.Utils { using System; /// <summary> /// /// </summary> public class JsonHelper { /// <summary> /// 序列化 /// </summary> /// <param name="obj">要序列化的實體</param> /// <returns>序列化後的字符串</returns> public static string SerializeToJson(object obj) { //Json.Net return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } /// <summary> /// 反序列化 /// </summary> /// <param name="json"></param> /// <returns></returns> public static Object DeserializeFromJson(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject(json); } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T DeserializeFromJson<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); } } }
namespace Apt.MWSGR.Infrastructure.Utils { using System.IO; using System.Web; public class FileLoadHelper { /// <summary> /// 文件根目錄 /// </summary> private static readonly string Root = HttpContext.Current.Server.MapPath("~/Files/"); /// <summary> /// 文件上傳 /// </summary> /// <param name="file"></param> /// <returns></returns> public static string Up(HttpPostedFile file) { // 根據MD5,計算存放路徑 string result = Md5Helper.GetMd5FromFile(file.InputStream); result = result.Replace('-', '\\'); string filename = result.Substring(result.LastIndexOf('\\')); string filePath = Path.Combine(Root, result.Substring(0, result.LastIndexOf('\\') + 1)); string fileType = file.FileName.Substring(file.FileName.LastIndexOf('.')); Directory.CreateDirectory(filePath); file.SaveAs(filePath.Trim('\\') + filename + fileType); return result+fileType; } } }
namespace Apt.MWSGR.Infrastructure.Utils { using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; public class Md5Helper { /// <summary> /// 將一個string 經過默認MD5算法獲得散列字符串 /// </summary> /// <param name="input">源字符串</param> /// <returns>散列字符串</returns> /// public static string GetMd5FromString(string input) { MD5 md5 = MD5.Create(); byte[] buffer = Encoding.UTF8.GetBytes(input); buffer = md5.ComputeHash(buffer); md5.Clear(); md5.Dispose(); return BitConverter.ToString(buffer); } /// <summary> /// 由文件全路徑獲取一個文件的MD5值,採用默認算法 /// </summary> /// <param name="path">文件全路徑</param> /// <returns></returns> public static string GetMd5FromFile(string path) { string res = ""; //MD5 md5 = MD5.Create(); using (FileStream fs = File.OpenRead(path)) { //byte[] buffer = md5.ComputeHash(fs); //md5.Clear(); //md5.Dispose(); //res = BitConverter.ToString(buffer); res = GetMd5FromFile(fs); } //md5.ComputeHash(); return res; } /// <summary> /// 由Stream獲得一個MD5字符串 /// </summary> /// <param name="stream">Stream</param> /// <returns>MD5</returns> public static string GetMd5FromFile(Stream stream) { string res = ""; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] buffer = md5.ComputeHash(stream); buffer = buffer.Skip(4).Take(8).ToArray(); md5.Clear(); md5.Dispose(); res = BitConverter.ToString(buffer); return res; } } }