代码:
public class KodCloudHelper
{
static readonly string kodCloudUrl = Configs.GetString("KodCloudUrl");
static readonly string kodCloudUser = Configs.GetString("KodCloudUser");
static readonly string kodCloudPwd = Configs.GetString("KodCloudPwd");
private readonly HttpClient Client;//如果不是一个client实例 可道云需要多传一个accessToken参数
public KodCloudHelper()
{
Client = new HttpClient();
}
/// <summary>
/// 获取accessToken
/// </summary>
/// <returns></returns>
public async Task<string> GetAccessToken()
{
var requestUrl = $"{kodCloudUrl}?user/loginSubmit&isAjax=1&getToken=1&name={kodCloudUser}&password={kodCloudPwd}";
return await GetKodApi(requestUrl);
}
/// <summary>
/// 获取文件列表
/// </summary>
/// <param name="path">文件夹路径</param>
/// <returns></returns>
public async Task<string> GetFileList(string path)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathList&path={path}";
return await GetKodApi(requestUrl);
}
/// <summary>
/// 批量获取文件属性
/// </summary>
/// <param name="getFilesAttrModel"></param>
/// <returns></returns>
public async Task<string> GetFileAttr(List<GetFilesAttrModel> getFilesAttrModels)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathInfo";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"dataArr", JsonConvert.SerializeObject(getFilesAttrModels)}
});
}
/// <summary>
/// 指定路径创建文件夹
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
public async Task<string> Mkdir(string dirPath)
{
var requestUrl = $"{kodCloudUrl}?explorer/mkdir";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"path", dirPath}
});
}
/// <summary>
/// 重命名文件或文件夹
/// </summary>
/// <param name="dirPath"></param>
/// <param name="newDirPath"></param>
/// <returns></returns>
public async Task<string> ReNameDir(string dirPath, string newDirPath)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathRname";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"path", dirPath},
{"rnameTo",newDirPath }
});
}
/// <summary>
/// 批量移动文件或文件夹
/// </summary>
/// <param name="moveFileModels">要移动的文件</param>
/// <param name="targetPath">要移动的地址</param>
/// <returns></returns>
public async Task<string> MoveFiles(List<MoveFileModel> moveFileModels,string targetPath)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathCuteDrag";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"dataArr", JsonConvert.SerializeObject(moveFileModels)},
{"path",targetPath}
});
}
/// <summary>
/// 批量复制文件或文件夹
/// </summary>
/// <param name="copyFileModels"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
public async Task<string> CopyFiles(List<CopyFileModel> copyFileModels, string targetPath)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathCopyDrag";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"dataArr", JsonConvert.SerializeObject(copyFileModels)},
{ "path",targetPath}
});
}
/// <summary>
/// 批量删除文件或文件夹
/// </summary>
/// <param name="deleteFileModels"></param>
/// <param name="shiftDelete">true代表彻底删除 false代表移动到回收站</param>
/// <returns></returns>
public async Task<string> DeleteFiles(List<DeleteFileModel> deleteFileModels,bool shiftDelete=false)
{
var requestUrl = $"{kodCloudUrl}?explorer/pathDelete";
var postDataDic = new Dictionary<string, string>()
{
{"dataArr", JsonConvert.SerializeObject(deleteFileModels)}
};
if (shiftDelete)
{
postDataDic.Add("shiftDelete", "1");
}
return await PostKodApi(requestUrl, postDataDic);
}
/// <summary>
/// 获取文件内容
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public async Task<string> GetFileContent(string fileName)
{
var requestUrl = $"{kodCloudUrl}?editor/fileGet";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"filename", fileName}
});
}
/// <summary>
/// 保存文件内容
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileStr">保存的内容字符串</param>
/// <param name="charSet">编码方式</param>
/// <returns></returns>
public async Task<string> SaveFileContent( string fileName,string fileStr,string charSet="utf-8")
{
var requestUrl = $"{kodCloudUrl}?editor/fileSave";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"path", fileName},
{"charset", charSet},
{"filestr",fileStr}
});
}
/// <summary>
/// 上传文件到可道云
/// </summary>
/// <param name="fullPath"></param>
/// <param name="tarGetFullPath"></param>
/// <returns></returns>
public async Task<bool> UploadFile(string fullPath, string tarGetFullPath)
{
var requestUrl = $"{kodCloudUrl}?explorer/fileUpload";
return await PostFileToKod(requestUrl, fullPath, tarGetFullPath);
}
/// <summary>
/// 下载可道云文件
/// </summary>
/// <param name="apiUrl">要获取的文件地址</param>
/// <param name="filePath">要储存的路径</param>
/// <param name="filename">要储存的文件名</param>
/// <returns></returns>
public async Task<bool> DownLoadFile(string targetFile, string filePath, string filename)
{
var requestUrl = $"{kodCloudUrl}?explorer/fileDownload&path={targetFile}";
return await GetFileToKod(requestUrl,filePath,filename);
}
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileType">要压缩文件格式;格式支持zip、tar、gz</param>
/// <param name="zipFileModel">要压缩的文件列表</param>
/// <returns></returns>
public async Task<string> ZipFile(List<ZipFileModel> zipFileModels, string fileType="zip")
{
var requestUrl = $"{kodCloudUrl}?explorer/zip";
return await PostKodApi(requestUrl, new Dictionary<string, string>()
{
{"dataArr", JsonConvert.SerializeObject(zipFileModels)},
{"fileType",fileType}
});
}
/// <summary>
/// 解压文件
/// </summary>
/// <param name="targetFile">要解压的文件</param>
/// <param name="targetFilePath">解压到(不传默认解压到当前文件夹)</param>
/// <returns></returns>
public async Task<string> UnZipFile(string targetFile,string targetFilePath="")
{
var requestUrl = $"{kodCloudUrl}?explorer/unzip";
var postDataDic = new Dictionary<string, string>()
{
{"path", targetFile}
};
if (!string.IsNullOrEmpty(targetFilePath))
{
postDataDic.Add("pathTo", targetFilePath);
}
return await PostKodApi(requestUrl, postDataDic);
}
#region http请求
/// <summary>
/// get方式调用可道云api
/// </summary>
/// <param name="apiUrl"></param>
/// <returns></returns>
internal async Task<string> GetKodApi(string apiUrl)
{
var requestUrl = apiUrl;
var response = await Client.GetAsync(requestUrl).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
var resultRecord = Record.Parse(result);
if (resultRecord.Get("code", true) is bool resultCode && resultCode)
{
return resultRecord.GetString("data");
}
return "";
}
/// <summary>
/// post方式请求可道云
/// </summary>
/// <param name="apiUrl"></param>
/// <param name="postDataDic"></param>
/// <returns></returns>
internal async Task<string> PostKodApi(string apiUrl, Dictionary<string,string> postDataDic)
{
var requestUrl = apiUrl;
HttpContent httpContent = new FormUrlEncodedContent(postDataDic);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await Client.PostAsync(requestUrl, httpContent).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
var resultRecord = Record.Parse(result);
if (resultRecord.Get("code", true) is bool resultCode && resultCode)
{
return resultRecord.GetString("data");
}
return "";
}
/// <summary>
/// post文件到可道云
/// </summary>
/// <param name="fullPath">要上传的文件路径</param>
/// <param name="tarGetFullPath">目标文件夹路径</param>
/// <returns></returns>
internal async Task<bool> PostFileToKod(string apiUrl,string fullPath,string tarGetFullPath)
{
string reqUrl = apiUrl;
string boundary = string.Format("----WebKitFormBoundary{0}", DateTime.Now.Ticks.ToString("x"));
MultipartFormDataContent content = new MultipartFormDataContent(boundary);
//content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
if (string.IsNullOrEmpty(fullPath) && !File.Exists(fullPath))
{
return false;
}
string fileName = Path.GetFileName(fullPath);
FileStream fStream = File.Open(fullPath, FileMode.Open, FileAccess.Read);
content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName);
content.Add(new StringContent(tarGetFullPath), "upload_to");
content.Add(new StringContent(fileName), "name");
var result = await Client.PostAsync(reqUrl, content);
try
{
if (result.IsSuccessStatusCode)
{
string rslt = result.Content.ReadAsStringAsync().Result;
var resultRecord = Record.Parse(rslt);
if (resultRecord.Get("code", true) is bool resultCode)
{
return resultCode;
}
return true;
}
}
catch (Exception ex)
{
}
finally
{
fStream.Close();
Client.Dispose();
}
return false;
}
/// <summary>
/// get方式获取可道云文件
/// </summary>
/// <param name="apiUrl">要获取的文件地址</param>
/// <param name="filePath">要储存的路径</param>
/// <param name="filename">要储存的文件名</param>
/// <returns></returns>
internal async Task<bool> GetFileToKod(string apiUrl, string filePath, string filename)
{
var url = apiUrl;
FileStream fs;
Client.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");//添加自主驱动 很重要,没细研究,确实添加上就能下载文件
Client.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");//添加数据格式
var bytes =await Client.GetByteArrayAsync(url);
if (File.Exists(filePath + "//" + filename))
{
File.Delete(filePath + "//" + filename);
}
fs = new FileStream(filePath + "//" + filename, FileMode.CreateNew);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
return true;
}
#endregion
}
实体类:
public class CopyFileModel
{
/// <summary>
/// 要复制的类型 file folder
/// </summary>
public string type { get; set; }
/// <summary>
/// 要复制的目标文件全路径
/// </summary>
public string path { get; set; }
}
public class DeleteFileModel
{
/// <summary>
/// 要删除的类型 file folder
/// </summary>
public string type { get; set; }
/// <summary>
/// 要删除的目标文件全路径
/// </summary>
public string path { get; set; }
}
public class GetFilesAttrModel
{
/// <summary>
/// 要获取的类型 file folder
/// </summary>
public string type { get; set; }
/// <summary>
/// 要获取文件的全路径
/// </summary>
public string path { get; set; }
}
public class MoveFileModel
{
/// <summary>
/// 要移动的类型 file folder
/// </summary>
public string type { get; set; }
/// <summary>
/// 要移动的目标文件全路径
/// </summary>
public string path { get; set; }
}
public class ZipFileModel
{
/// <summary>
/// 要添加到压缩包的文件类型 file folder
/// </summary>
public string type { get; set; }
/// <summary>
/// 要添加到压缩包的文件目标文件全路径
/// </summary>
public string path { get; set; }
}
//dataArr: [{"type":"folder","path":"/test/folder1/"},{"type":"folder","path":"/test/folder2/af.txt"}]
// 创建文件名为dataArr中第一个path 追加压缩文件扩展名;例如上面的就会压缩成/test/folder1.zip