using DevExpress.Utils.DirectXPaint;
using DevExpress.XtraEditors;
using Gs.DevApp.ToolBox;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
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;
}
public string parentGuid
{
get;
set;
}
///
/// 改变事件
///
public event EventHandler UpChanged;
#region 文件上传
///
/// 选择上传文件
///
///
///
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;
}
}
///
/// 确定上传
///
///
///
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)
{
UcLoading _loading = new UcLoading();
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));
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);
}
_loading.Close();
}
#endregion
}
}