文件上传在系统中是一个很常见的功能,现在将angular文件上传的代码总结一下。在此特别感谢同事陈卫兵提供的思路总结。
1、前端页面
(1)提交的时候用ng-submit进行提交。
(2)form表单的enctype属性改为multipart/form-data
(3)增加一个文件上传的input
本文共 6353 字,大约阅读时间需要 21 分钟。
文件上传在系统中是一个很常见的功能,现在将angular文件上传的代码总结一下。在此特别感谢同事陈卫兵提供的思路总结。
1、前端页面
(1)提交的时候用ng-submit进行提交。
(2)form表单的enctype属性改为multipart/form-data
(3)增加一个文件上传的input
2、angular中的处理
(1)在define中要引入fileUpload和angularFileUpload模块
配置paths和shimfileUpload: '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'); }); }
3、后台的处理
(1)后台中的数据和文件是分别获取的。
// 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(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; ////// /// public class JsonHelper { ////// 序列化 /// /// 要序列化的实体 ///序列化后的字符串 public static string SerializeToJson(object obj) { //Json.Net return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } ////// 反序列化 /// /// ///public static Object DeserializeFromJson(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject(json); } /// /// 反序列化 /// ////// /// public static T DeserializeFromJson (string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject (json); } }}
namespace Apt.MWSGR.Infrastructure.Utils{ using System.IO; using System.Web; public class FileLoadHelper { ////// 文件根目录 /// private static readonly string Root = HttpContext.Current.Server.MapPath("~/Files/"); ////// 文件上传 /// /// ///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 { ////// 将一个string 通过默认MD5算法得到散列字符串 /// /// 源字符串 ///散列字符串 /// 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); } ////// 由文件全路径获取一个文件的MD5值,采用默认算法 /// /// 文件全路径 ///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; } /// /// 由Stream得到一个MD5字符串 /// /// Stream ///MD5 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; } }}
转载于:https://my.oschina.net/u/1416844/blog/284770