首先添加两个引用,用于解压ZIP(ZipArchive类)
前端POST方式上传ZIP文件。
using GDSMBLL;
using GDSMCommon;
using GDSMModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace GDSMPlateForm.Controllers
{
public class UserUploadPackageController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
[HttpPost]
public string UploadFile()
{
string returnHtmlUrl = "";
ValidateHelper vh = new ValidateHelper();
string guid = Guid.NewGuid().ToString();
HttpRequest request = HttpContext.Current.Request;
string user_id = request["user_id"];
HttpFileCollection fileCollection = request.Files;
if (fileCollection.Count > 0)
{
HttpPostedFile file = fileCollection[0];
string format = Path.GetExtension(file.FileName);
#region 验证
if (!vh.IsValidateFileExtension(file.FileName, FileType.package))
{
returnHtmlUrl = JsonHelper.RequstFail("文件格式不支持");
}
else if (file.ContentLength > vh.GetResTypeSize(file.FileName) && vh.GetResTypeSize(file.FileName) != 0)
{
return JsonHelper.RequstFail("文件超过指定大小");
}
#endregion
string webroot = HttpContext.Current.Server.MapPath("~");
//ZIP路径
string zipPath = "/Content/userh5static/" + user_id;
//创建zip目录
if (!Directory.Exists(webroot + zipPath))
{
Directory.CreateDirectory(webroot + zipPath);
}
zipPath += "/";
try
{
string zipName = guid + format;
file.SaveAs(webroot + zipPath + zipName);
//创建解压目录
string htmlPath = zipPath + guid;
if (!Directory.Exists(webroot + htmlPath))
{
Directory.CreateDirectory(webroot + htmlPath);
}
//解压zip文件到htmlPath目录
using (var archive = new ZipArchive(file.InputStream, ZipArchiveMode.Read))
{
try
{
archive.ExtractToDirectory(webroot + htmlPath);
}
catch (Exception)
{
}
}
string htmlIndexPath = webroot + htmlPath + "/index";
var htmlfiles = Directory.GetFiles(htmlIndexPath, "*.html", SearchOption.TopDirectoryOnly);
if (htmlfiles.Count() > 0)
{
returnHtmlUrl = htmlfiles[0].Replace(webroot, "").Replace("\","/");
}
#region 信息存入数据库
JHUserH5Static userH5Static = new JHUserH5Static();
userH5Static.file_id = guid;
userH5Static.file_name = zipName;
userH5Static.file_type = format.Substring(1);
userH5Static.file_oldname = file.FileName;
userH5Static.file_path = zipPath + zipName;
userH5Static.pstatus = "normal";
userH5Static.create_user_id = user_id;
userH5Static.create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
userH5Static.file_oldpath = returnHtmlUrl;
userH5Static.file_img = "";
JHUserH5StaticBL H5StaticBL = new JHUserH5StaticBL();
H5StaticBL.Insert(userH5Static);
#endregion
}
catch (Exception ex)
{
returnHtmlUrl = JsonHelper.RequestSuccessNoData("上传出错:" + ex.Message);
}
}
return returnHtmlUrl;
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}