绝对高分求客户端向服务器上传与下载文件的程序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了绝对高分求客户端向服务器上传与下载文件的程序相关的知识,希望对你有一定的参考价值。
我想用VB做一个程序可以向服务器上传文件,然后保存在服务器硬盘空间里,当我想阅读时,可以在服务器上找到这个文件,并把它打开,进行浏览.把它下载到本机来打开也可以.(如果你知道其中某方面也麻烦你告诉我),在这里我先谢谢各位来帮忙啦,快来帮一下小弟吧,各位大侠.
xiaozhuge0825@163.com,这是我的邮箱,谢谢你啦!我的QQ是77977652请多多帮忙.
一 WEB部分
1 首先把WEB页获得本地要上传的文件名
2 WEB通过脚本把本地文件名(绝对路径)给客户端组件
3 WEB脚本控制组件开始传送数据
4 最后判断是否传输成功
二 组件部分
1 建立INTERNET连接
2 连接FTP服务器
3 获得本地文件名(绝对路径)
4 返回远程即将保存的文件名
5 传送数据
6 判断是否传输成功,返回状态
WEB页获取本地文件
组件返回远程文件名
组件传送数据
返回
本例在VB6.0 +WIN2000+ IIS5.0 + SERV-U 5.0 下调试成功
VB部分
一、建立一个ActiveX DLL工程
二、更改工程名FtpConn
三、更改类名:clsPutFile
四、加入一个空模块到工程中,此模块主要对需要使用的函数进行声明,在此不多做解释,代码如下:
Option Explicit
Declare Function GetProcessHeap Lib "kernel32" () As Long
Declare Function HeapAlloc Lib "kernel32" (ByVal hHeap As Long, ByVal dwFlags As Long, ByVal dwBytes As Long) As Long
Declare Function HeapFree Lib "kernel32" (ByVal hHeap As Long, ByVal dwFlags As Long, lpMem As Any) As Long
Public Const HEAP_ZERO_MEMORY = &H8
Public Const HEAP_GENERATE_EXCEPTIONS = &H4
Declare Sub CopyMemory1 Lib "kernel32" Alias "RtlMoveMemory" ( _
hpvDest As Any, ByVal hpvSource As Long, ByVal cbCopy As Long)
Declare Sub CopyMemory2 Lib "kernel32" Alias "RtlMoveMemory" ( _
hpvDest As Long, hpvSource As Any, ByVal cbCopy As Long)
Public Const MAX_PATH = 260
Public Const NO_ERROR = 0
Public Const FILE_ATTRIBUTE_READONLY = &H1
Public Const FILE_ATTRIBUTE_HIDDEN = &H2
Public Const FILE_ATTRIBUTE_SYSTEM = &H4
Public Const FILE_ATTRIBUTE_DIRECTORY = &H10
Public Const FILE_ATTRIBUTE_ARCHIVE = &H20
Public Const FILE_ATTRIBUTE_NORMAL = &H80
Public Const FILE_ATTRIBUTE_TEMPORARY = &H100
Public Const FILE_ATTRIBUTE_COMPRESSED = &H800
Public Const FILE_ATTRIBUTE_OFFLINE = &H1000
Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Public Const ERROR_NO_MORE_FILES = 18
Public Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" _
(ByVal hFind As Long, lpvFindData As WIN32_FIND_DATA) As Long
Public Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" _
(ByVal hFtpSession As Long, ByVal lpszSearchFile As String, _
lpFindFileData As WIN32_FIND_DATA, ByVal dwFlags As Long, ByVal dwContent As Long) As Long
Public Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _
(ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, ByVal dwContext As Long) As Boolean
Public Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" _
(ByVal hFtpSession As Long, ByVal lpszLocalFile As String, _
ByVal lpszRemoteFile As String, _
ByVal dwFlags As Long, ByVal dwContext As Long) As Boolean
Public Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias "FtpSetCurrentDirectoryA" _
(ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean
' Initializes an application's use of the Win32 Internet functions
Public Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" _
(ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, _
ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
' User agent constant.
Public Const scUserAgent = "vb wininet"
' Use registry access settings.
Public Const INTERNET_OPEN_TYPE_PRECONFIG = 0
Public Const INTERNET_OPEN_TYPE_DIRECT = 1
Public Const INTERNET_OPEN_TYPE_PROXY = 3
Public Const INTERNET_INVALID_PORT_NUMBER = 0
Public Const FTP_TRANSFER_TYPE_ASCII = &H1
Public Const FTP_TRANSFER_TYPE_BINARY = &H1
Public Const INTERNET_FLAG_PASSIVE = &H8000000
' Opens a HTTP session for a given site.
Public Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" _
(ByVal hInternetSession As Long, ByVal sServerName As String, ByVal nServerPort As Integer, _
ByVal sUsername As String, ByVal sPassword As String, ByVal lService As Long, _
ByVal lFlags As Long, ByVal lContext As Long) As Long
Public Const ERROR_INTERNET_EXTENDED_ERROR = 12003
Public Declare Function InternetGetLastResponseInfo Lib "wininet.dll" Alias "InternetGetLastResponseInfoA" ( _
lpdwError As Long, _
ByVal lpszBuffer As String, _
lpdwBufferLength As Long) As Boolean
' Number of the TCP/IP port on the server to connect to.
Public Const INTERNET_DEFAULT_FTP_PORT = 21
Public Const INTERNET_DEFAULT_GOPHER_PORT = 70
Public Const INTERNET_DEFAULT_HTTP_PORT = 80
Public Const INTERNET_DEFAULT_HTTPS_PORT = 443
Public Const INTERNET_DEFAULT_SOCKS_PORT = 1080
Public Const INTERNET_OPTION_CONNECT_TIMEOUT = 2
Public Const INTERNET_OPTION_RECEIVE_TIMEOUT = 6
Public Const INTERNET_OPTION_SEND_TIMEOUT = 5
Public Const INTERNET_OPTION_USERNAME = 28
Public Const INTERNET_OPTION_PASSWORD = 29
Public Const INTERNET_OPTION_PROXY_USERNAME = 43
Public Const INTERNET_OPTION_PROXY_PASSWORD = 44
' Type of service to access.
Public Const INTERNET_SERVICE_FTP = 1
Public Const INTERNET_SERVICE_GOPHER = 2
Public Const INTERNET_SERVICE_HTTP = 3
' Opens an HTTP request handle.
Public Declare Function HttpOpenRequest Lib "wininet.dll" Alias "HttpOpenRequestA" _
(ByVal hHttpSession As Long, ByVal sVerb As String, ByVal sObjectName As String, ByVal sVersion As String, _
ByVal sReferer As String, ByVal something As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long
' Brings the data across the wire even if it locally cached.
Public Const INTERNET_FLAG_RELOAD = &H80000000
Public Const INTERNET_FLAG_KEEP_CONNECTION = &H400000
Public Const INTERNET_FLAG_MULTIPART = &H200000
Public Const GENERIC_READ = &H80000000
Public Const GENERIC_WRITE = &H40000000
' Sends the specified request to the HTTP server.
Public Declare Function HttpSendRequest Lib "wininet.dll" Alias "HttpSendRequestA" (ByVal _
hHttpRequest As Long, ByVal sHeaders As String, ByVal lHeadersLength As Long, ByVal sOptional As _
String, ByVal lOptionalLength As Long) As Integer
' Queries for information about an HTTP request.
Public Declare Function HttpQueryInfo Lib "wininet.dll" Alias "HttpQueryInfoA" _
(ByVal hHttpRequest As Long, ByVal lInfoLevel As Long, ByRef sBuffer As Any, _
ByRef lBufferLength As Long, ByRef lIndex As Long) As Integer
' The possible values for the lInfoLevel parameter include:
Public Const HTTP_QUERY_CONTENT_TYPE = 1
Public Const HTTP_QUERY_CONTENT_LENGTH = 5
Public Const HTTP_QUERY_EXPIRES = 10
Public Const HTTP_QUERY_LAST_MODIFIED = 11
Public Const HTTP_QUERY_PRAGMA = 17
Public Const HTTP_QUERY_VERSION = 18
Public Const HTTP_QUERY_STATUS_CODE = 19
Public Const HTTP_QUERY_STATUS_TEXT = 20
Public Const HTTP_QUERY_RAW_HEADERS = 21
Public Const HTTP_QUERY_RAW_HEADERS_CRLF = 22
Public Const HTTP_QUERY_FORWARDED = 30
Public Const HTTP_QUERY_SERVER = 37
Public Const HTTP_QUERY_USER_AGENT = 39
Public Const HTTP_QUERY_SET_COOKIE = 43
Public Const HTTP_QUERY_REQUEST_METHOD = 45
Public Const HTTP_STATUS_DENIED = 401
Public Const HTTP_STATUS_PROXY_AUTH_REQ = 407
' Add this flag to the about flags to get request header.
Public Const HTTP_QUERY_FLAG_REQUEST_HEADERS = &H80000000
Public Const HTTP_QUERY_FLAG_NUMBER = &H20000000
' Reads data from a handle opened by the HttpOpenRequest function.
Public Declare Function InternetReadFile Lib "wininet.dll" _
(ByVal hFile As Long, ByVal sBuffer As String, ByVal lNumBytesToRead As Long, _
lNumberOfBytesRead As Long) As Integer
Public Declare Function InternetWriteFile Lib "wininet.dll" _
(ByVal hFile As Long, ByVal sBuffer As String, _
ByVal lNumberOfBytesToRead As Long, _
lNumberOfBytesRead As Long) As Integer
Public Declare Function FtpOpenFile Lib "wininet.dll" Alias _
"FtpOpenFileA" (ByVal hFtpSession As Long, _
ByVal sFileName As String, ByVal lAccess As Long, _
ByVal lFlags As Long, ByVal lContext As Long) As Long
Public Declare Function FtpDeleteFile Lib "wininet.dll" _
Alias "FtpDeleteFileA" (ByVal hFtpSession As Long, _
ByVal lpszFileName As String) As Boolean
Public Declare Function InternetSetOption Lib "wininet.dll" Alias "InternetSetOptionA" _
(ByVal hInternet As Long, ByVal lOption As Long, ByRef sBuffer As Any, ByVal lBufferLength As Long) As Integer
Public Declare Function InternetSetOptionStr Lib "wininet.dll" Alias "InternetSetOptionA" _
(ByVal hInternet As Long, ByVal lOption As Long, ByVal sBuffer As String, ByVal lBufferLength As Long) As Integer
' Closes a single Internet handle or a subtree of Internet handles.
Public Declare Function InternetCloseHandle Lib "wininet.dll" _
(ByVal hInet As Long) As Integer
' Queries an Internet option on the specified handle
Public Declare Function InternetQueryOption Lib "wininet.dll" Alias "InternetQueryOptionA" _
(ByVal hInternet As Long, ByVal lOption As Long, ByRef sBuffer As Any, ByRef lBufferLength As Long) As Integer
' Returns the version number of Wininet.dll.
Public Const INTERNET_OPTION_VERSION = 40
' Contains the version number of the DLL that contains the Windows Internet
' functions (Wininet.dll). This structure is used when passing the
' INTERNET_OPTION_VERSION flag to the InternetQueryOption function.
Public Type tWinInetDLLVersion
lMajorVersion As Long
lMinorVersion As Long
End Type
' Adds one or more HTTP request headers to the HTTP request handle.
Public Declare Function HttpAddRequestHeaders Lib "wininet.dll" Alias "HttpAddRequestHeadersA" _
(ByVal hHttpRequest As Long, ByVal sHeaders As String, ByVal lHeadersLength As Long, _
ByVal lModifiers As Long) As Integer
' Flags to modify the semantics of this function. Can be a combination of these values:
' Adds the header only if it does not already exist; otherwise, an error is returned.
Public Const HTTP_ADDREQ_FLAG_ADD_IF_NEW = &H10000000
' Adds the header if it does not exist. Used with REPLACE.
Public Const HTTP_ADDREQ_FLAG_ADD = &H20000000
' Replaces or removes a header. If the header value is empty and the header is found,
' it is removed. If not empty, the header value is replaced
Public Const HTTP_ADDREQ_FLAG_REPLACE = &H80000000
五、输入类代码,代码如下:
Option Explicit
Dim bActiveSession As Boolean
Dim hOpen As Long
Dim hConnection As Long
Dim scUserAgent As String
Dim strServer As String
Dim strUser As String
Dim strPassword As String
Dim nFlag As Long
Dim bRet As Boolean
Dim szFileLocal As String
Dim szFileRemote As String
Dim dwType As Integer
Public Function PUTFILE() As Boolean
On Error Resume Next
hOpen = InternetOpen(scUserAgent, INTERNET_OPEN_TYPE_DIRECT, vbNullString, vbNullString, 0)
hConnection = InternetConnect(hOpen, strServer, INTERNET_INVALID_PORT_NUMBER, strUser, strPassword, INTERNET_SERVICE_FTP, nFlag, 0)
bRet = FtpPutFile(hConnection, szFileLocal, szFileRemote, _
dwType, 0)
Call CloseConn
PUTFILE = bRet
End Function
Sub CloseConn()
If hConnection <> 0 Then InternetCloseHandle hConnection
hConnection = 0
End Sub
Function getRemoteName(filename)
Dim arrName() As String
arrName = Split(filename, ".")
Randomize
getRemoteName = Date & CInt(Rnd * 1000) & "." & arrName(UBound(arrName))
End Function
Private Sub Class_Initialize()
scUserAgent = "My FTP"
strServer = "www.XXX.cn"
strUser = "Username"
strPassword = "Password"
nFlag = INTERNET_FLAG_PASSIVE
szFileLocal = "DefultLocalFileName"
szFileRemote = "DefultRemoteFileName"
dwType = 1
End Sub
Public Property Get connServer() As Variant
connServer = strServer
End Property
Public Property Let connServer(ByVal vNewValue As Variant)
strServer = vNewValue
End Property
Public Property Get connUser() As Variant
connUser = strUser
End Property
Public Property Let connUser(ByVal vNewValue As Variant)
strUser = vNewValue
End Property
Public Property Get connPassword() As Variant
connPassword = strPassword
End Property
Public Property Let connPassword(ByVal vNewValue As Variant)
strPassword = vNewValue
End Property
Public Property Let LocalFileName(ByVal vNewValue As Variant)
szFileLocal = vNewValue
szFileRemote = getRemoteName(vNewValue)
End Property
Public Property Get RemoteFileName() As Variant
RemoteFileName = szFileRemote
End Property
六、生成DLL
七、使用VB6的打包工具打包成“Internet ActiveX 安装包”,这是,VB打包后,还会给一个例子的html文件
八、建立HTML文件
<HTML>
<HEAD>
<TITLE>FtpConn.CAB</TITLE>
</HEAD>
<BODY>
<OBJECT ID="clsPutFile"
CLASSID="CLSID:D9BACC8F-0A99-46DA-ADA3-F1C25A48AA78"
CODEBASE="FtpConn.CAB#version=1,0,0,0">
</OBJECT>
<INPUT type="file" name="FileName"><button onclick="go()">GO~!</button>
<SCRIPT LANGUAGE="javascript">
<!-- by Newrocky 2004-12-7 QQ:1936234
function go()
if (FileName.value!='')
clsPutFile.LocalFileName=FileName.value;
alert(clsPutFile.RemoteFileName);//查看远程文件名
if (clsPutFile.PutFile()) //开始传送文件,如果返回true则成功,反之失败
alert('上传文件成功!');
else
alert('上传文件失败!')
else
alert('请选择您要上传的文件');
//-->
</SCRIPT>
</BODY>
</HTML>
ok~!
===============下载部分=============
首先,声明一些变量
Dim strCommand As String
Dim strWebPage As String
为了动态设置Winsock控件的一些属性,在“开始”按钮的Click事件加入以下代码。
Winsock1.RemoteHost="192.168.100.101" '设置连接的IP地址
Winsock1.RemotePort = 80 '设置连接的远程端口号
Winsock1.Connect '开始连接远程计算机。
当Winsock控件连接操作完成,就可以传送FTP命令给服务器了,因此在Winsock控件的Connect事件中加入以下代码:
On Error Resume Next '在错误处理程序结束后,恢复原有的运行
strWebPage= " 192.168.100.101/main.htm" '设置要下载的文件'添加FTP中取得文件的命令(GET)
strCommand = "GET " + strWebPage + " HTTP/1.0" + vbCrLf
strCommand = strCommand + "Accept: */*" + vbCrLf
strCommand = strCommand + "Accept: text/html" + vbCrLf
strCommand = strCommand + vbCrLf '必须以vbCrLf结束命令
Winsock1.SendData strCommand '向远程计算机发送命令
当Winsock控件获取到数据时,需要对数据进行处理,本例中将获取的内容显示在文本框控件中,因此在Winsock控件的DataArrival事件加入以下代码:
On Error Resume Next '在错误处理程序结束后,恢复原有的运行
Dim webData As String
Winsock1.GetData webData,vbString '获取当前的数据块
Text1.Text = Text1.Text + webData '显示接收到的数据 参考技术A 一楼的是一种方法(没有详细看),但是好像太繁杂,有比较简单的。
您的Email?我给您一个。 参考技术B 汗,专家的答案MS还要借用FTP,这样太麻烦了吧。。 参考技术C 你要把Server程序放到公网服务器上?自己写的程序不安全的。别让黑客利用了。最好学是使用FTP软件。给自己添个账号就可以实现了。
如何使用 CSOM 从/向 SharePoint 2013 下载/上传文件?
【中文标题】如何使用 CSOM 从/向 SharePoint 2013 下载/上传文件?【英文标题】:How to download/upload files from/to SharePoint 2013 using CSOM? 【发布时间】:2013-06-08 01:38:05 【问题描述】:我正在开发一个 Win8(WinRT、C#、XAML)客户端应用程序 (CSOM),它需要从 SharePoint 2013 下载/上传文件。
如何进行下载/上传?
【问题讨论】:
【参考方案1】:上传文件
使用File.SaveBinaryDirect Method 将文件上传到 SharePoint 网站(包括 SharePoint Online):
using (var clientContext = new ClientContext(url))
using (var fs = new FileStream(fileName, FileMode.Open))
var fi = new FileInfo(fileName);
var list = clientContext.Web.Lists.GetByTitle(listTitle);
clientContext.Load(list.RootFolder);
clientContext.ExecuteQuery();
var fileUrl = String.Format("0/1", list.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
下载文件
使用File.OpenBinaryDirect Method从 SharePoint 网站(包括 SharePoint Online)下载文件:
using (var clientContext = new ClientContext(url))
var list = clientContext.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
clientContext.Load(list);
clientContext.Load(listItem, i => i.File);
clientContext.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
var fileName = Path.Combine(filePath,(string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
fileInfo.Stream.CopyTo(fileStream);
【讨论】:
Vadim,1. 我收到关于 ICredentials 和路径的错误。我需要做什么吗。 2. 您已经在 XML 文件中注释了此article 描述了访问 SharePoint 内容的各种选项。您可以在 REST 和 CSOM 之间进行选择。如果可能,我会尝试 CSOM。文件上传/下载具体在this文章中有很好的描述。
总体说明:
//First construct client context, the object which will be responsible for
//communication with SharePoint:
var context = new ClientContext(@"http://site.absolute.url")
//then get a hold of the list item you want to download, for example
var list = context.Web.Lists.GetByTitle("Pipeline");
var query = CamlQuery.CreateAllItemsQuery(10000);
var result = list.GetItems(query);
//note that data has not been loaded yet. In order to load the data
//you need to tell SharePoint client what you want to download:
context.Load(result, items=>items.Include(
item => item["Title"],
item => item["FileRef"]
));
//now you get the data
context.ExecuteQuery();
//here you have list items, but not their content (files). To download file
//you'll have to do something like this:
var item = items.First();
//get the URL of the file you want:
var fileRef = item["FileRef"];
//get the file contents:
FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());
using (var memory = new MemoryStream())
byte[] buffer = new byte[1024 * 64];
int nread = 0;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
memory.Write(buffer, 0, nread);
memory.Seek(0, SeekOrigin.Begin);
// ... here you have the contents of your file in memory,
// do whatever you want
避免直接使用流,先将其读入内存。网络绑定的流不一定支持流操作,更不用说性能了。因此,如果您正在从该流中读取图片或解析文档,您最终可能会遇到一些意外行为。
附带说明一下,我有一个相关的问题:上述代码的性能,因为您在每次文件请求时都会受到一些惩罚。见here。是的,您需要 4.5 完整的 .NET 配置文件。
【讨论】:
【参考方案3】:File.OpenBinaryDirect 在您使用 Oauth accestoken 时可能会导致异常 解释于This Article
代码应该写成下面这样避免异常
Uri filename = new Uri(filepath);
string server = filename.AbsoluteUri.Replace(filename.AbsolutePath,
"");
string serverrelative = filename.AbsolutePath;
Microsoft.SharePoint.Client.File file =
this.ClientContext.Web.GetFileByServerRelativeUrl(serverrelative);
this.ClientContext.Load(file);
ClientResult<Stream> streamResult = file.OpenBinaryStream();
this.ClientContext.ExecuteQuery();
return streamResult.Value;
【讨论】:
【参考方案4】:这个评论有点晚了,但我会在这里留下我使用 SharePoin Online 库的结果,它非常易于在您的项目中使用和实施,只需转到 .Net 的 NuGet 管理员并添加 Microsoft.SharePoint。 CSOM 到您的项目中。
[https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/][1]
以下代码 sn-p 将帮助您将凭据连接到您的 SharePoint 网站,您还可以从特定网站和文件夹读取和下载文件。
using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;
using ClientOM = Microsoft.SharePoint.Client;
namespace MvcApplication.Models.Home
public class SharepointModel
public ClientContext clientContext get; set;
private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
private string LibraryUrl = "Shared Documents/Invoices/";
private string UserName = "someone.surname@somecompany.com";
private string Password = "********";
private Web WebClient get; set;
public SharepointModel()
this.Connect();
public void Connect()
try
using (clientContext = new ClientContext(ServerSiteUrl))
var securePassword = new SecureString();
foreach (char c in Password)
securePassword.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
WebClient = clientContext.Web;
catch (Exception ex)
throw (ex);
public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
try
HttpPostedFileBase file = null;
for (int f = 0; f < Request.Files.Count; f++)
file = Request.Files[f] as HttpPostedFileBase;
string[] SubFolders = LibraryUrl.Split('/');
string filename = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
file.SaveAs(path);
clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
clientContext.ExecuteQuery();
//https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
clientContext.ExecuteQuery();
string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
var folderToBindTo = documentsList.RootFolder.Folders;
var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();
var fileCreationInformation = new FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
//Update the metadata for a field having name "DocType"
uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
return "";
catch (Exception ex)
throw (ex);
public string DownloadFiles()
try
string tempLocation = @"c:\Downloads\Sharepoint\";
System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
foreach (FileInfo file in di.GetFiles())
file.Delete();
FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
clientContext.Load(files);
clientContext.ExecuteQuery();
if (clientContext.HasPendingRequest)
clientContext.ExecuteQuery();
foreach (ClientOM.File file in files)
FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
clientContext.ExecuteQuery();
var filePath = tempLocation + file.Name;
using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
fileInfo.Stream.CopyTo(fileStream);
return "";
catch (Exception ex)
throw (ex);
然后在这种情况下从控制器调用函数 MVC ASP.NET 以下列方式完成。
using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;
namespace MvcApplication.Controllers
public class SharepointController : MvcBoostraBaseController
[HttpPost]
public ActionResult Upload(FormCollection form)
try
SharepointModel sharepointModel = new SharepointModel();
return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
catch (Exception ex)
return ThrowJSONError(ex);
public ActionResult Download(string ServerUrl, string RelativeUrl)
try
SharepointModel sharepointModel = new SharepointModel();
return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
catch (Exception ex)
return ThrowJSONError(ex);
如果你需要这个源代码,你可以访问我的 github 仓库
https://github.com/israelz11/MvcBoostrapTestSharePoint/【讨论】:
【参考方案5】:Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
Try
destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
Dim down As Stream = System.IO.File.Create(destinationPath)
Dim a As Integer = fi.Stream.ReadByte()
While a <> -1
down.WriteByte(CType(a, Byte))
a = fi.Stream.ReadByte()
End While
Catch ex As Exception
ToLog(Type.ERROR, ex.Message)
End Try
End Sub
【讨论】:
【参考方案6】:虽然这是一篇旧帖子并且有很多答案,但在这里我有我的代码版本,可以使用 CSOM(c#) 将文件上传文件到 sharepoint 2013
我希望如果您正在下载和上传文件,那么您知道如何创建Clientcontext
对象和Web
对象
/* Assuming you have created ClientContext object and Web object*/
string listTitle = "List title where you want your file to upload";
string filePath = "your file physical path";
List oList = web.Lists.GetByTitle(listTitle);
clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileInfo.Url = fileName;
File fileToUpload = fileCollection.Add(fileInfo);
clientContext.ExecuteQuery();
fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
if (oList.EnableMinorVersions)
fileToUpload.Publish("your publish comment");
clientContext.ExecuteQuery();
if (oList.EnableModeration)
fileToUpload.Approve("your approve comment");
clientContext.ExecuteQuery();
这里是下载代码
List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
clientContext.Load(oList);
clientContext.Load(oList.RootFolder);
clientContext.Load(oList.RootFolder.Files);
clientContext.ExecuteQuery();
FileCollection fileCollection = oList.RootFolder.Files;
File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
clientContext.Load(SP_file);
clientContext.ExecuteQuery();
var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
var Sp_Stream = fileInformation.Stream;
Sp_Stream.CopyTo(Local_stream);
我认为仍然有不同的方式可以用于上传和下载。
【讨论】:
【参考方案7】:只是建议 SharePoint 2013 在线和本地文件编码为 UTF-8 BOM。 确保您的文件是 UTF-8 BOM,否则您上传的 html 和脚本可能无法在浏览器中正确呈现。
【讨论】:
【参考方案8】:我建议您阅读一些有关您可以使用 CSOM 做什么的 Microsoft 文档。这可能是您正在寻找的一个示例,但 msdn 中记录了一个庞大的 API。
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
// Assume that the web has a list named "Announcements".
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
// Assume there is a list item with ID=1.
ListItem listItem = announcementsList.Items.GetById(1);
// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!";
listItem.Update();
context.ExecuteQuery();
发件人:http://msdn.microsoft.com/en-us/library/fp179912.aspx
【讨论】:
这与下载/上传文件无关。您正在使用此代码更新列表项以上是关于绝对高分求客户端向服务器上传与下载文件的程序的主要内容,如果未能解决你的问题,请参考以下文章
客户端是如何上传数据到FTP服务器和从FTP服务器下载文件的?