ASP.NET 上傳檔案到共享資料夾
阿新 • • 發佈:2020-08-12
建立共享資料夾參考資料:https://www.cnblogs.com/dansediao/p/5712657.html
上傳檔案程式碼
web.config
<!--上傳檔案配置,UploadPath值一定是伺服器ip,內網ip最好-->
<add key="UploadPath" value="\\172.21.0.10\File" />
<add key="DownloadPath" value="http://x.x.x.x:80/" />
<add key="UserName" value="ShareUser" />
<add key=" Password" value="P@ssw0rd" />
工具方法
public static string GetConfigString(string key, string @default = "")
{
return ConfigurationManager.AppSettings[key] ?? @default;
}
/// <summary>
/// 根據檔名(包含副檔名)獲取要儲存的資料夾名稱
/// </summary>
public class FileHelper
{
/// <summary>
/// 根據檔名(包含副檔名)獲取要儲存的資料夾名稱
/// </summary>
/// <param name="fileName">檔名(包含副檔名)</param>
public static string GetSaveFolder(string fileName)
{
var fs = fileName.Split('.');
var ext = fs[fs.Length - 1];
var str = string.Empty;
var t = ext.ToLower();
switch (t)
{
case "jpg":
case "jpeg":
case "png":
case "gif":
str = "images";
break;
case "mp4":
case "mkv":
case "rmvb":
str = "video";
break;
case "apk":
case "wgt":
str = "app";
break;
case "ppt":
case "pptx":
case "doc":
case "docx":
case "xls":
case "xlsx":
case "pdf":
str = "file";
break;
default:
str = "file";
break;
}
return str;
}
}
/// <summary>
/// 記錄日誌幫助類
/// </summary>
public class WriteHelper
{
public static void WriteFile(object data)
{
try
{
string path = $@"C:\Log\";
var filename = $"Log.txt";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
TextWriter tw = new StreamWriter(Path.Combine(path, filename), true); //true在檔案末尾新增資料
tw.WriteLine($"----產生時間:{DateTime.Now:yyyy-MM-dd HH:mm:ss}---------------------------------------------------------------------");
tw.WriteLine(data.ToJson());
tw.Close();
}
catch (Exception e)
{
}
}
}
常量
/// <summary>
/// 檔案上傳配置項
/// </summary>
public class FileUploadConst
{
/// <summary>
/// 上傳地址
/// </summary>
public static string UploadPath => ConfigHelper.GetConfigString("UploadPath");
/// <summary>
/// 檔案訪問/下載地址
/// </summary>
public static string DownloadPath => ConfigHelper.GetConfigString("DownloadPath");
/// <summary>
/// 訪問共享目錄使用者名稱
/// </summary>
public static string UserName => ConfigHelper.GetConfigString("UserName");
/// <summary>
/// 訪問共享目錄密碼
/// </summary>
public static string Password => ConfigHelper.GetConfigString("Password");
}
具體上傳檔案程式碼
/// <summary>
/// 上傳檔案到共享資料夾
/// </summary>
[HttpPost, Route("api/Upload/UploadAttachment")]
[AllowAnonymous]
public ServiceResponse<UploadRespModel> UploadAttachment()
{
var viewModel = new UploadRespModel();
var code = 200;
var msg = "上傳失敗!";
var path = FileUploadConst.UploadPath; //@"\\172.16.10.130\Resource";
var s = connectState(path, FileUploadConst.UserName, FileUploadConst.Password);
if (s)
{
var filelist = HttpContext.Current.Request.Files;
if (filelist.Count > 0)
{
var file = filelist[0];
var fileName = file.FileName;
var blobName = FileHelper.GetSaveFolder(fileName);
path = $@"{path}\{blobName}\";
fileName = $"{DateTime.Now:yyyyMMddHHmmss}{fileName}";
//共享資料夾的目錄
var theFolder = new DirectoryInfo(path);
var remotePath = theFolder.ToString();
Transport(file.InputStream, remotePath, fileName);
viewModel.SaveUrl = $"{blobName}/{fileName}";
viewModel.DownloadUrl = PictureHelper.GetFileFullPath(viewModel.SaveUrl);
msg = "上傳成功";
}
}
else
{
code = CommonConst.Code_OprateError;
msg = "連結伺服器失敗";
}
return ServiceResponse<UploadRespModel>.SuccessResponse(msg, viewModel, code);
}
/// <summary>
/// 連線遠端共享資料夾
/// </summary>
/// <param name="path">遠端共享資料夾的路徑</param>
/// <param name="userName">使用者名稱</param>
/// <param name="passWord">密碼</param>
private static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
WriteHelper.WriteFile($"dosLine:{dosLine}");
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
WriteHelper.WriteFile($"errormsg:{errormsg}");
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
WriteHelper.WriteFile(ex);
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
/// <summary>
/// 向遠端資料夾儲存本地內容,或者從遠端資料夾下載檔案到本地
/// </summary>
/// <param name="inFileStream">要儲存的檔案的路徑,如果儲存檔案到共享資料夾,這個路徑就是本地檔案路徑如:@"D:\1.avi"</param>
/// <param name="dst">儲存檔案的路徑,不含名稱及副檔名</param>
/// <param name="fileName">儲存檔案的名稱以及副檔名</param>
private static void Transport(Stream inFileStream, string dst, string fileName)
{
WriteHelper.WriteFile($"目錄-Transport:{dst}");
if (!Directory.Exists(dst))
{
Directory.CreateDirectory(dst);
}
dst = dst + fileName;
if (!File.Exists(dst))
{
WriteHelper.WriteFile($"檔案不存在,開始儲存");
var outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);
var buf = new byte[inFileStream.Length];
int byteCount;
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
{
outFileStream.Write(buf, 0, byteCount);
}
WriteHelper.WriteFile($"儲存完成");
inFileStream.Flush();
inFileStream.Close();
outFileStream.Flush();
outFileStream.Close();
}
}