using Gs.DevApp.ToolBox;
|
using System;
|
using System.Configuration;
|
using System.IO;
|
using System.Net.Http;
|
using System.Threading.Tasks;
|
using System.Windows.Forms;
|
|
namespace Gs.DevApp.UserControl
|
{
|
public partial class UCUpFile : DevExpress.XtraEditors.XtraUserControl
|
{
|
public UCUpFile()
|
{
|
InitializeComponent();
|
//上传附件
|
btnUpSelect.Click += BtnUpSelect_Click;
|
btnUp.Click += BtnUp_Click;
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
public string parentGuid
|
{
|
get;
|
set;
|
}
|
/// <summary>
|
///
|
/// </summary>
|
public string parentGroup
|
{
|
get;
|
set;
|
}
|
|
/// <summary>
|
/// 改变事件
|
/// </summary>
|
public event EventHandler UpChanged;
|
|
#region 文件上传
|
|
/// <summary>
|
/// 选择上传文件
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="e"></param>
|
private void BtnUpSelect_Click(object sender, EventArgs e)
|
{
|
var openFileDialog = new OpenFileDialog();
|
// 设置初始目录
|
openFileDialog.InitialDirectory = "c:\\";
|
// 设置文件过滤选项,如:"文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"
|
openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
|
// 设置标题
|
openFileDialog.Title = "选择文件";
|
// 显示对话框
|
var result = openFileDialog.ShowDialog();
|
// 确认用户没有取消操作
|
if (result == DialogResult.OK)
|
{
|
// 获取选中的文件路径
|
var filePath = openFileDialog.FileName;
|
Console.WriteLine($"选中的文件: {filePath}");
|
txtUpUrl.Text = filePath;
|
}
|
}
|
|
/// <summary>
|
/// 确定上传
|
/// </summary>
|
/// <param name="sender"></param>
|
/// <param name="e"></param>
|
private async void BtnUp_Click(object sender, EventArgs e)
|
{
|
var WebApiUrl = ConfigurationSettings.AppSettings.Get("WebApiUrl");
|
var address = WebApiUrl + "MesFile/UploadFile";
|
var filePath = txtUpUrl.Text.Trim();
|
if (string.IsNullOrEmpty(filePath))
|
{
|
Gs.DevApp.ToolBox.MsgHelper.ShowError("请选择你需要上传的文件!");
|
return;
|
}
|
var apiUrl = address; // 替换为你的API地址
|
await UploadFileAsync(apiUrl, filePath);
|
if (UpChanged != null) UpChanged(this, e);
|
}
|
|
private async Task UploadFileAsync(string url, string filePath)
|
{
|
string _parentGuid = parentGuid;
|
using (var httpClient = new HttpClient())
|
try
|
{
|
using (var form = new MultipartFormDataContent())
|
{
|
httpClient.DefaultRequestHeaders.Add("token",
|
UtilityHelper.GetBasicAuthTicket());
|
using (var fs = File.OpenRead(filePath))
|
using (var streamContent = new StreamContent(fs))
|
{
|
form.Add(streamContent, "file", _parentGuid + "~" + Path.GetFileName(filePath) + "~" + parentGroup);
|
var response = await httpClient.PostAsync(url, form);
|
var responseString =
|
await response.Content.ReadAsStringAsync();
|
// MessageBox.Show(responseString);
|
txtUpUrl.Text = "";
|
}
|
}
|
}
|
catch (Exception ex)
|
{
|
Gs.DevApp.ToolBox.MsgHelper.ShowError(ex.Message);
|
|
}
|
|
}
|
|
#endregion
|
}
|
}
|