Starts in:
2 DAYS
17 HRS
12 MIN
21 SEC
Starts in:
2 D
17 H
12 M
21 S
Open Closed

how can i upload file?the file extentiion is 'csv' OR 'pnx' #8257


User avatar
0
njis.abp3 created
<InputFile id="img" OnChange="OnChange" style="max-width: 400px" class="form-control" multiple accept='.csv,.pnx,application/octet-stream'>
</InputFile>

protected async Task OnChange(InputFileChangeEventArgs e)
{
    var selectedFiles = e.GetMultipleFiles(100);
    foreach (var item in selectedFiles)
    {

        await OnSubmit(item);
    }
}
protected async Task OnSubmit(IBrowserFile browserFile)
{
    if (browserFile == null) return;
    var ext = Path.GetExtension(browserFile.Name);
    ImportFile.FileNameWithoutExt = Path.GetFileNameWithoutExtension(browserFile.Name);

    // 创建一个新的 MemoryStream 实例
    var memoryStream = new MemoryStream();
    try
    {
        // 打开浏览器文件的流
        using var browserFileStream = browserFile.OpenReadStream(maxAllowedSize: 1024 * 1024 * 30);
        // 将浏览器文件流的内容复制到 MemoryStream
        await browserFileStream.CopyToAsync(memoryStream);
        // 重置 MemoryStream 的位置,以便从头开始读取
        memoryStream.Seek(0, SeekOrigin.Begin);
        // 创建 RemoteStreamContent 对象时,确保传递正确的参数
        var remoteStreamContent = new RemoteStreamContent(memoryStream, browserFile.Name, ext);
        var result = await PlanningTasksAppService.UploadAsync(remoteStreamContent);
        displayProgress = true;
        if (result.Code == 200)
        {
            ImportFile.FilePath = result.Data;
        }
        else
        {
            await Message.Error($"操作失败:原因-{result.Msg}", "导入");
        }
        displayProgress = false;
    }
    finally
    {
        // 确保 MemoryStream 被释放
        memoryStream.Dispose();
    }
    //StateHasChanged();
}

api:
[HttpPost]
[Route("api/sleeve-milling/planning-tasks/uploadAsync")]
public async Task<ResultMsg<string>> UploadAsync(IRemoteStreamContent content)
{
    return await _planningTasksAppService.UploadAsync(content);
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="content">文件流</param>
/// <returns>返回信息</returns>
[AllowAnonymous]
public virtual async Task<ResultMsg<string>> UploadAsync(IRemoteStreamContent remoteStreamContent)
{
    var result = new ResultMsg<string>();
    try
    {
        var uploadPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", _sleeveMillingSettingManager.ImportFileUrl(), "Import", DateTime.Now.ToString("yyyyMM"));
        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);
        var fileName = $"{CommonHelper.GetDateTimeNowString()}{Path.GetExtension(remoteStreamContent.FileName)}";
        var tempfilename = Path.Combine(uploadPath, fileName);
        using var remoteStream = remoteStreamContent.GetStream();
        // 确保远程流是可读的
        if (!remoteStream.CanRead)
        {
            throw new InvalidOperationException("The remote stream does not support reading.");
        }

        // 将远程流的内容复制到一个可写的内存流中
        using var memoryStream = new MemoryStream();
        await remoteStream.CopyToAsync(memoryStream); // 使用异步方法复制

        // 重置内存流的位置,以便从头开始读取
        memoryStream.Seek(0, SeekOrigin.Begin);

        // 保存文件
        using var fileStream = new FileStream(tempfilename, FileMode.Create);
        await memoryStream.CopyToAsync(fileStream); // 使用异步方法保存文件
        result.Data = tempfilename;
    }
    catch (Exception ex)
    {
        result.Code = 0;
        result.Msg = ex.Message;
    }
    return result;
}

Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2 Uncaught (in promise) Error: System.FormatException: The format of value '.csv' is invalid. at System.Net.Http.Headers.MediaTypeHeaderValue.CheckMediaTypeFormat(String mediaType, String parameterName) at System.Net.Http.Headers.MediaTypeHeaderValue..ctor(String mediaType) at Volo.Abp.Http.Client.ClientProxying.ClientProxyRequestPayloadBuilder.GenerateFormPostDataAsync(ActionApiDescriptionModel action, IReadOnlyDictionary2 methodArguments) at Volo.Abp.Http.Client.ClientProxying.ClientProxyRequestPayloadBuilder.BuildContentAsync(ActionApiDescriptionModel action, IReadOnlyDictionary2 methodArguments, IJsonSerializer jsonSerializer, ApiVersionInfo apiVersion) at Volo.Abp.Http.Client.ClientProxying.ClientProxyBase1.RequestAsync(ClientProxyRequestContext requestContext) at Volo.Abp.Http.Client.ClientProxying.ClientProxyBase1.RequestAsync[T](ClientProxyRequestContext requestContext) at Volo.Abp.Http.Client.ClientProxying.ClientProxyBase`1.RequestAsync[T](String methodName, ClientProxyRequestTypeValue arguments) at NJIS.IMP.SleeveMilling.PlanningTasks.PlanningTaskClientProxy.UploadAsync(IRemoteStreamContent content) in /home/njis/builds/hCwriuD-/0/imp/njis.imp.sleevemilling/services/SleeveMilling/src/NJIS.IMP.SleeveMilling.HttpApi.Client/ClientProxies/NJIS/PlanningTaskClientProxy.Generated.cs:line 24 at NJIS.IMP.SleeveMilling.Blazor.Pages.SleeveMilling.PlanningTasks.PlanningTasks_ImportFile.OnSubmit(IBrowserFile browserFile) in /home/njis/builds/hCwriuD-/0/imp/njis.imp.sleevemilling/services/SleeveMilling/src/NJIS.IMP.SleeveMilling.Blazor/Pages/SleeveMilling/PlanningTasks/PlanningTasks_ImportFile.razor.cs:line 514 at NJIS.IMP.SleeveMilling.Blazor.Pages.SleeveMilling.PlanningTasks.PlanningTasks_ImportFile.OnChange(InputFileChangeEventArgs e) in /home/njis/builds/hCwriuD-/0/imp/njis.imp.sleevemilling/services/SleeveMilling/src/NJIS.IMP.SleeveMilling.Blazor/Pages/SleeveMilling/PlanningTasks/PlanningTasks_ImportFile.razor.cs:line 493 at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at ut.endInvokeDotNetFromJS (Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2:2731) at ge._invokeClientMethod (Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2:46734) at ge._processIncomingData (Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2:44227) at connection.onreceive (Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2:37911) at e.onmessage (Blazor.LeptonXTheme.Global.35A6E73A3F1D4D9626F4EA86E14C4597.js?_v=638668299822289926:2:65625)

how to solve this problem?


3 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    The format of value '.csv' is invalid.

    you can try

    var ext = MimeTypeMap.GetMimeType(browserFile.Name.Split('.').Last().ToLower())
    
  • User Avatar
    0
    njis.abp3 created

    MimeTypeMap:Can you show the package of reference?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    <PackageVersion Include="MimeTypeMapOfficial" Version="1.0.17" />

Made with ❤️ on ABP v9.1.0-preview. Updated on November 20, 2024, 13:06