Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c# - .Net Core 3.1 MVC Ajax File Upload (without using a form object)

I am using .NET Core 3.1 MVC infrastructure.

I want to upload files to Azure Blob Storage with ajax.

But there is no form object in my View.cshtml. It should not be a form object either, because another operation of mine does not allow me to use a form.

Isn't it possible to upload files with ajax without using form object?

Microsoft has an example, but the form has always been used. Isn't it possible to do this without posting a form object?

Microsoft Source : https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1

I might have friends who don't understand what I mean by form. I am sharing the sample code block.

<form enctype="multipart/form-data" method="post"> 
  <input asp-for="FileUpload.FormFile" type="file">             
  <input asp-page-handler="Upload" class="btn" type="submit" value="Upload" />
</form>

Thank you so much,

question from:https://stackoverflow.com/questions/66063756/net-core-3-1-mvc-ajax-file-upload-without-using-a-form-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can upload files directly from the web page directly and not using the form object: use file as you wish.

To do this, you need to get a SAS token with write permission and on the web page, you can use Azure storage JS SDK to upload files directly.

You can go through this official sample to do this.

I also write a simple demo with uploading progress for you for a quick test :

<html>

<body>

    <button id="select-button">Select and upload files</button>
    <input type="file" id="file-input" multiple style="display: none;" />
    <div id="showProgress"></div>


    <p><b>Status:</b></p>
    <p id="status" style="height:160px; width: 593px; overflow: scroll;" />

    
</body>
<script src="./azure-storage-blob.js" charset="utf-8"></script>
<script>

const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const status = document.getElementById("status");

const reportStatus = message => {
    status.innerHTML += `${message}<br/>`;
    status.scrollTop = status.scrollHeight;
}

const accountName = "<your storage account name>";
const sasToken = "<your sas token without '?' >";
const containerName = "<your container name>";
const containerURL = new azblob.ContainerURL(
    `https://${accountName}.blob.core.windows.net/${containerName}?${sasToken}`,
    azblob.StorageURL.newPipeline(new azblob.AnonymousCredential));

const uploadFiles = async () => {
    try {
        reportStatus("Uploading files...");
        const promises = [];
        for (var fileIndex = 0; fileIndex < fileInput.files.length; fileIndex++) {
            const file = fileInput.files[fileIndex];
            const blockBlobURL = azblob.BlockBlobURL.fromContainerURL(containerURL, file.name);

            document.getElementById('showProgress').innerHTML += file.name +":<div id='progress-"+ file.name +"'></div>"
            

            var blobUploadOptions = {
                blockSize: 4 * 1024 * 1024, // 4MB block size
                parallelism: 20, // 20 concurrency
                progress: function (ev) {
                    var percentdone = ((ev.loadedBytes / file.size) * 100);
                    var progessItem = document.getElementById('progress-' + file.name);
                    progessItem.innerHTML = percentdone.toFixed(2) + "%";                     
                }
            };
            var promise = azblob.uploadBrowserDataToBlockBlob(
                azblob.Aborter.none, file, blockBlobURL,blobUploadOptions);
            
            promise.then((result)=>{
                var progessItem = document.getElementById('progress-' + file.name);
                progessItem.innerHTML += "  <a href="+result._response.request.url+">file link</a>" 
                
            });

            promises.push(promise);
        }
        await Promise.all(promises);

        reportStatus("Done.");
    } catch (error) {
        console.log(error)
    }
}

selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);


</script>

</html>

Please make sure that you have enabled CORS before you run this demo.

Result:

enter image description here

enter image description here

Let me know if you have any further questions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...