C#实现图片上传(PC端和APP)保存及 跨域上传说明

A-PC端:

1-页面--multiple是控制单张还是多张图片上传

<input id="BusRoute" type="file" class="btn btn-default btn-lg" style="height:34px;padding-top:5px;padding-bottom:5px;" multiple />

2-后台获取图片文件:

HttpFileCollection pcFileColl = HttpContext.Current.Request.Files;

3-保存示例:

#region 创建目录
//完整存储路径
string completeUrl = "";
//相对等级路径
string relativeUrl = "";
//string saveTempPath = "~/Resources/Pic";
//string picUploadPath = HttpContext.Current.Server.MapPath(saveTempPath);
//添加根目录
completeUrl = @"\\10.0.8.52\YuanXinFiles\Office\"; ;
//添加一级目录
string relativeOneUrl = DateTime.Now.Year.ToString();
completeUrl += "\\" + relativeOneUrl;
relativeUrl += "\\" + relativeOneUrl;
if (!Directory.Exists(completeUrl))
{
Directory.CreateDirectory(completeUrl);
}
//添加二级目录
string relativeTwoUrl = DateTime.Now.Month.ToString();
completeUrl += "\\" + relativeTwoUrl;
relativeUrl += "\\" + relativeTwoUrl;
if (!Directory.Exists(completeUrl))
{
Directory.CreateDirectory(completeUrl);
}
#endregion
//保存
HttpFileCollection picColl = picModel.PcFileColl;
for (var i = 0; i < picColl.Count; i++)
{
HttpPostedFile file = picColl[i];
//保存图片
//保存至指定目录
file.SaveAs(completeUrl + "\\" + fileName);
}

B-APP:

前端页面长什么样不管了,后台拿到的是base64的字符串集合.

1-保存示例:

#region 创建目录
//完整存储路径
string completeUrl = "";
//相对等级路径
string relativeUrl = "";
//string saveTempPath = "~/Resources/Pic";
//string picUploadPath = HttpContext.Current.Server.MapPath(saveTempPath);
//添加根目录
completeUrl = @"\\10.0.8.52\YuanXinFiles\Office\"; ;
//添加一级目录
string relativeOneUrl = DateTime.Now.Year.ToString();
completeUrl += "\\" + relativeOneUrl;
relativeUrl += "\\" + relativeOneUrl;
if (!Directory.Exists(completeUrl))
{
Directory.CreateDirectory(completeUrl);
}
//添加二级目录
string relativeTwoUrl = DateTime.Now.Month.ToString();
completeUrl += "\\" + relativeTwoUrl;
relativeUrl += "\\" + relativeTwoUrl;
if (!Directory.Exists(completeUrl))
{
Directory.CreateDirectory(completeUrl);
}
#endregion
//保存
byte[] bytes = Convert.FromBase64String(strPic.picCode);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter();
System.Drawing.Bitmap map = new Bitmap(memStream);
Image image = (Image)map;
string imageName = Guid.NewGuid().ToString("N");
//保存图片
image.Save(completeUrl + "\\" + imageName + "." + strPic.picType); //保存图片

C-跨域保存问题:

跨域的常见场景如下图所示:我们通过电脑的网络影射,连接到所需要的目录,这里添加上拥有权限的人员账号即可访问目标文件夹,那么使用C#代码如何获得访问权限呢?

要获取以上访问权限,需要引用一个类和添加一些简单代码:

1-访问代码:

/// <summary>
/// 通过指定用户执行上次图片操作
/// </summary>
/// <param name="uploadAction"></param>
public void UploadFileByUser(Action uploadAction)
{
//参考类:D:\SourceCode\MCSFramework\02.Develop\MobileWebApp\YuanXin\Services\FileUploadService\Controllers\UploadController.cs
//无法通过权限认证--只能通过外网访问
try
{
var ip = "10.0.8.52";
var domain = "sinooceanland";
var username = ConfigurationManager.AppSettings["uploadUserName"].ToString(); //配置的用户名
var pwd = ConfigurationManager.AppSettings["uploadPassword"].ToString(); //配置的密码
var root = ConfigurationManager.AppSettings["uploadRootPath"].ToString(); //配置的文件根路径
using (NetworkShareAccesser.Access(ip, domain, username, pwd)) //建立连接
{
uploadAction(); //图片保存代码
}
}
catch (System.Exception e)
{
}
}

2-必须类:

public class NetworkShareAccesser : IDisposable
{
private string _remoteUncName;
private string _remoteComputerName;
public string RemoteComputerName
{
get
{
return this._remoteComputerName;
}
set
{
this._remoteComputerName = value;
this._remoteUncName = @"\\" + this._remoteComputerName;
}
}
public string UserName
{
get;
set;
}
public string Password
{
get;
set;
}
#region Consts
private const int RESOURCE_CONNECTED = 0x00000001;
private const int RESOURCE_GLOBALNET = 0x00000002;
private const int RESOURCE_REMEMBERED = 0x00000003;
private const int RESOURCETYPE_ANY = 0x00000000;
private const int RESOURCETYPE_DISK = 0x00000001;
private const int RESOURCETYPE_PRINT = 0x00000002;
private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
private const int RESOURCEUSAGE_CONTAINER = 0x00000002;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const int CONNECT_PROMPT = 0x00000010;
private const int CONNECT_REDIRECT = 0x00000080;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_CMD_SAVECRED = 0x00001000;
private const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion
#region Errors
private const int NO_ERROR = 0;
private const int ERROR_ACCESS_DENIED = 5;
private const int ERROR_ALREADY_ASSIGNED = 85;
private const int ERROR_BAD_DEVICE = 1200;
private const int ERROR_BAD_NET_NAME = 67;
private const int ERROR_BAD_PROVIDER = 1204;
private const int ERROR_CANCELLED = 1223;
private const int ERROR_EXTENDED_ERROR = 1208;
private const int ERROR_INVALID_ADDRESS = 487;
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_INVALID_PASSWORD = 1216;
private const int ERROR_MORE_DATA = 234;
private const int ERROR_NO_MORE_ITEMS = 259;
private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
private const int ERROR_NO_NETWORK = 1222;
private const int ERROR_BAD_PROFILE = 1206;
private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
private const int ERROR_DEVICE_IN_USE = 2404;
private const int ERROR_NOT_CONNECTED = 2250;
private const int ERROR_OPEN_FILES = 2401;
#endregion
#region PInvoke Signatures
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
[DllImport("Mpr.dll")]
private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
);
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
#endregion
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
/// </summary>
/// <param name="remoteComputerName"></param>
/// <returns></returns>
public static NetworkShareAccesser Access(string remoteComputerName)
{
return new NetworkShareAccesser(remoteComputerName);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="domainOrComuterName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
domainOrComuterName + @"\" + userName,
password);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
userName,
password);
}
private NetworkShareAccesser(string remoteComputerName)
{
RemoteComputerName = remoteComputerName;
this.ConnectToShare(this._remoteUncName, null, null, true);
}
private NetworkShareAccesser(string remoteComputerName, string userName, string password)
{
RemoteComputerName = remoteComputerName;
UserName = userName;
Password = password;
this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
}
private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE
{
dwType = RESOURCETYPE_DISK,
lpRemoteName = remoteUnc
};
int result;
if (promptUser)
{
result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
}
else
{
result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
}
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
private void DisconnectFromShare(string remoteUnc)
{
int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
this.DisconnectFromShare(this._remoteUncName);
}
}

以上所述是小编给大家介绍的C#实现图片上传(PC端和APP)保存及 跨域上传说明,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • c#批量上传图片到服务器示例分享

    客户端代码: 复制代码 代码如下: /// <summary>/// 批量上传图片/// </summary>/// <param name="srcurl">服务器路径</param>/// <param name="imagesPath">图片文件夹路径</param>/// <param name="files">图片名称</param>publ

  • c#图片上传和显示的实现方法

    由于需要图片上传的功能,所以花了一些时间网上找相关资料终于搞定,效果图如下: 下面的是解决方案截图和上传的图片截图: 具体实现代码如下: 1.界面代码 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadPic.aspx.cs" Inherits="Pic_Try.UploadPic" %> <!DOCTYPE html PUBLIC

  • C#保存上传来的图片示例代码

    复制代码 代码如下: [HttpPost] public string UploadImage() { //string ss = Request.Form["uploadFile"]; //return ss; HttpPostedFileBase uploadFile = Request.Files[0]; string fileName = uploadFile.FileName; int fileSize = uploadFile.ContentLength; string f

  • 基于C# winform实现图片上传功能的方法

    本文所述实例实现将一张图片上传到指定的文件夹,然后在窗体上的PictrueBox控件中显示出来. 具体功能代码如下: private void btnUpload_Click(object sender, EventArgs e) { //创建一个对话框对象 OpenFileDialog ofd = new OpenFileDialog(); //为对话框设置标题 ofd.Title = "请选择上传的图片"; //设置筛选的图片格式 ofd.Filter = "图片格式|*

  • C#图片上传效果实例分析

    本文实例讲述了C#图片上传效果实现方法.分享给大家供大家参考.具体如下: <%@ Page Title="" Language="C#" MasterPageFile="~/Default.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> <asp:Conte

  • C# 最齐全的上传图片方法

    方法里包括了图片大小限制.图片尺寸.文件内容等等的判断... 该案例是mvc下的demo,支持单张图片上传. public ActionResult Upload() { string imgurl = ""; foreach (string key in Request.Files) { //这里只测试上传第一张图片file[0] HttpPostedFileBase file0 = Request.Files[key]; //转换成byte,读取图片MIME类型 Stream st

  • C#判断上传文件是否是图片以防止木马上传的方法

    很多时候木马程序会伪装成其他格式的文件上传到网站,最常见的如图片格式.本文就以C#为例讲述C#判断上传文件是否是图片以防止木马上传的方法,具体方法如下: 方法一:用image对象判断是否为图片 /// <summary> /// 判断文件是否为图片 /// </summary> /// <param name="path">文件的完整路径</param> /// <returns>返回结果</returns> pu

  • C#实现图片上传与浏览切换的方法

    本文以一个完整实例讲述了C#实现图片上传与浏览切换的方法,对于进行C#程序设计来说具有一定的借鉴价值.分享给大家供大家参考. 具体实现代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %> <!DOCTYPE html PUBLIC "-//W3C//

  • ASP.NET(C#)实现一次性动态上传多张图片的代码(多个文件)

    在做asp.net的Web开发的时候,我们经常会遇到一次性上传多个文件的需求.通常我们的解决方法是固定放多个上传文件框,这样的解决办法显然是不合理的,因为一次上传多个,就意味着数量不确定.因此我们就要让这些文件上传框动态添加,下面我以我做的一个图库管理中的上传图片的功能为例 先看效果: 打开的初始界面: 默认是上传一个图片,但当我们点"增加图片"按钮时可以实现选择多个图片及其描述同时上传,本功能限制一次最多只能上传8张,且每张图片大小不超过1M,这个大家可根据实际情况更改! 如图: 下

  • C#使用Socket上传并保存图片的方法

    本文实例讲述了C#使用Socket上传并保存图片的方法.分享给大家供大家参考.具分析如下: 使用string filename = openFile.FileName;即返回带全路径的文件名 Path.GetFileNameWithoutExtension(filename)即可获得不带路径.后缀名的文件名. 上传图片使用二进制 tcp协议上传的 客户端代码: using System; using System.Collections.Generic; using System.Compone

  • c#多图片上传并生成缩略图的实例代码

    前台代码: 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&q

随机推荐