文件上传在系统中是一个很常见的功能,如今将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; } } }