- Published on
dotnet core large file upload with resume using tus and react/nextjs
Table of Contents
Large file upload with dotnet and react with tus
In this post we will see how to do large file upload in chunks with resume capabilities in dotnet core as a backend and react/nextjs as frontend.
dotnet project
Create the .net project using this following command
dotnet new webapp -n FileUpload -o .Add tusdotnet nuget package
dotnet add package tusdotnet --version 2.4.0Enable Cors
Update the ConfigureServices
services.AddCors();Update Configure method
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders(CorsHelper.GetExposedHeaders()));Configure MaxRequestBodySize
Update Configure method and make sure this is the first pipeline request.
app.Use((context, next) =>
{
// Default limit was changed some time ago. Should work by setting MaxRequestBodySize to null using ConfigureKestrel but this does not seem to work for IISExpress.
// Source: https://github.com/aspnet/Announcements/issues/267
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
return next.Invoke();
});Configure tus
Update Configure method
app.UseTus(httpContext => new DefaultTusConfiguration
{
Store = new TusDiskStore(@"C:\tusfiles\"),
UrlPath = "/files",
Events = new Events
{
OnFileCompleteAsync = async eventContext =>
{
// eventContext.FileId is the id of the file that was uploaded.
// eventContext.Store is the data store that was used (in this case an instance of the TusDiskStore)
// A normal use case here would be to read the file and do some processing on it.
ITusFile file = await eventContext.GetFileAsync();
var result = await DoSomeProcessing(file, eventContext.CancellationToken).ConfigureAwait(false);
if (!result)
{
//throw new MyProcessingException("Something went wrong during processing");
}
}
}
});Make sure to put this before UseRouting and UseAuthorization
Nextjs App
Create next app
yarn create next-app --typescriptAdd tus package
yarn add tus-js-clientCreate file upload component
import React from "react";
import { Upload } from "tus-js-client";
interface Props {}
const FileUpload = (props: Props) => {
const onFileChange = (e: any) => {
var file = e.target.files[0];
const upload = new Upload(file, {
endpoint: "https://localhost:5001/files",
retryDelays: [0, 1000, 3000, 5000],
metadata: {
filename: file.name,
filetype: file.type,
},
onError: function (error) {
console.log("Failed because: " + error);
},
onProgress: function (bytesUploaded, bytesTotal) {
var percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
console.log(bytesUploaded, bytesTotal, percentage + "%");
},
onSuccess: function () {
console.log("Download %s from %s", upload.file.name, upload.url);
},
});
// Check if there are any previous uploads to continue.
upload.findPreviousUploads().then(function (previousUploads) {
// Found previous uploads so we select the first one.
if (previousUploads.length) {
upload.resumeFromPreviousUpload(previousUploads[0]);
}
// Start the upload
upload.start();
});
};
return (
<div className="text-center text-2xl p-6">
<input type="file" name="file" id="" onChange={onFileChange} />
</div>
);
};
export default FileUpload;Add the component to the page.
<FileUpload></FileUpload>Github Repo: https://github.com/antosubash/LargeFileUploadSample
Related Posts
Continue reading with these related articles
Your First SimpleModule Module: a Table, an Endpoint and a React Page
Build a bookmarks module in a fresh SimpleModule app, from scaffold to migration, validated API, React page and tests.
Introducing SimpleModule: A Modular Monolith Framework for Python, Built on FastAPI and Inertia
A tour of SimpleModule, where each Python feature is a self-contained module with its own tables, endpoints and React pages, shipped as one FastAPI and Inertia app.
Introducing SimpleModule: A Modular Monolith Framework for .NET 10
Meet SimpleModule, an experimental .NET 10 framework that uses Roslyn source generators to build modular monoliths with compile-time module discovery, full-stack type safety, and Inertia.js-powered React UIs.