admin管理员组文章数量:1356924
The javascript for drag and drop files can show the file information but when I save the file on the server on vb, I get Request.Files.Count is zero. Also I saw error on debug in VS Upload failed: TypeError: Failed to fetch at UniversalFileUploader.uploadFilesToServer (C:\WebApplication1\Default.aspx:167:17) at HTMLInputElement. (https://localhost:44388/Default.aspx:120:26) {stack: 'TypeError: Failed to fetch at UniversalFi…(https://localhost:44388/Default.aspx:120:26)', message: 'Failed to fetch'}
I think it is fetch issue. Would someone have idea?
The javascript class constructor:
constructor(options = {}) {
this.config = {
dropZoneSelector: options.dropZoneSelector || '#file-drop-zone',
allowedTypes: options.allowedTypes || ['*'],
maxFileSize: options.maxFileSize || 50 * 1024 * 1024, // 50MB
maxFiles: options.maxFiles || 5,
maxTotalSize: options.maxTotalSize || 100 * 1024 * 1024, // 100MB total
uploadUrl: options.uploadUrl || 'Default.aspx' // Ensure correct upload URL
};
this.uploadedFiles = [];
this.init();
}
The javascript for fetch in my javascript class
uploadFilesToServer(filesArray) {
const formData = new FormData();
filesArray.forEach(file => {
formData.append("files", file);
});
console.log("Uploading files...", formData);
fetch(this.config.uploadUrl, {
method: "POST",
body: formData
})
.then(response => response.text()) // Change from .json() to .text() for debugging
.then(data => {
console.log("Server Response:", data);
alert("Upload Successful!");
})
.catch(error => {
console.error("Upload failed:", error);
alert("Upload Failed. Check console for details.");
});
}
// Initialize uploader
const uploader = new UniversalFileUploader({
dropZoneSelector: '#file-drop-zone',
maxTotalSize: 100 * 1024 * 1024, // 100MB
maxFileSize: 50 * 1024 * 1024, // 50MB per file
allowedTypes: ['image/jpeg', 'image/png', 'application/pdf']
});
There is vb code behind:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
If Request.Files.Count > 0 Then
Dim uploadedFiles As HttpFileCollection = Request.Files
Dim savedFiles As New List(Of String)()
For i As Integer = 0 To uploadedFiles.Count - 1
Dim file As HttpPostedFile = uploadedFiles(i)
If file.ContentLength > 0 Then
Dim savePath As String = Server.MapPath("~/Uploads/" & file.FileName)
file.SaveAs(savePath)
savedFiles.Add(file.FileName)
End If
Next
Response.ContentType = "application/json"
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(New With {.success = True, .files = savedFiles}))
Response.End()
End If
End Sub
I added the enctype on form tab
<form id="form1" runat="server" enctype="multipart/form-data">
The javascript for drag and drop files can show the file information but when I save the file on the server on vb, I get Request.Files.Count is zero. Also I saw error on debug in VS Upload failed: TypeError: Failed to fetch at UniversalFileUploader.uploadFilesToServer (C:\WebApplication1\Default.aspx:167:17) at HTMLInputElement. (https://localhost:44388/Default.aspx:120:26) {stack: 'TypeError: Failed to fetch at UniversalFi…(https://localhost:44388/Default.aspx:120:26)', message: 'Failed to fetch'}
I think it is fetch issue. Would someone have idea?
The javascript class constructor:
constructor(options = {}) {
this.config = {
dropZoneSelector: options.dropZoneSelector || '#file-drop-zone',
allowedTypes: options.allowedTypes || ['*'],
maxFileSize: options.maxFileSize || 50 * 1024 * 1024, // 50MB
maxFiles: options.maxFiles || 5,
maxTotalSize: options.maxTotalSize || 100 * 1024 * 1024, // 100MB total
uploadUrl: options.uploadUrl || 'Default.aspx' // Ensure correct upload URL
};
this.uploadedFiles = [];
this.init();
}
The javascript for fetch in my javascript class
uploadFilesToServer(filesArray) {
const formData = new FormData();
filesArray.forEach(file => {
formData.append("files", file);
});
console.log("Uploading files...", formData);
fetch(this.config.uploadUrl, {
method: "POST",
body: formData
})
.then(response => response.text()) // Change from .json() to .text() for debugging
.then(data => {
console.log("Server Response:", data);
alert("Upload Successful!");
})
.catch(error => {
console.error("Upload failed:", error);
alert("Upload Failed. Check console for details.");
});
}
// Initialize uploader
const uploader = new UniversalFileUploader({
dropZoneSelector: '#file-drop-zone',
maxTotalSize: 100 * 1024 * 1024, // 100MB
maxFileSize: 50 * 1024 * 1024, // 50MB per file
allowedTypes: ['image/jpeg', 'image/png', 'application/pdf']
});
There is vb code behind:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
If Request.Files.Count > 0 Then
Dim uploadedFiles As HttpFileCollection = Request.Files
Dim savedFiles As New List(Of String)()
For i As Integer = 0 To uploadedFiles.Count - 1
Dim file As HttpPostedFile = uploadedFiles(i)
If file.ContentLength > 0 Then
Dim savePath As String = Server.MapPath("~/Uploads/" & file.FileName)
file.SaveAs(savePath)
savedFiles.Add(file.FileName)
End If
Next
Response.ContentType = "application/json"
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(New With {.success = True, .files = savedFiles}))
Response.End()
End If
End Sub
I added the enctype on form tab
<form id="form1" runat="server" enctype="multipart/form-data">
Share
Improve this question
asked Mar 28 at 14:40
CDVSCDVS
112 bronze badges
2
|
1 Answer
Reset to default 1Are you using any 3rd party up-loader here? And any particular reason why you trying to roll your own up-loader?
There is a good number of high quality up-loaders (even free) that will:
Have a drag + drop hot spot
Have a working progress bar
Up-loads files in "small chunks", so the browser does not look
to have frozen.
Since using small chunks, then limited memory is used, and this
allows files of un-limited file size.
Assuming webforms, then I use the AjaxFileUpLoader from the Ajaxtoolkit. (it's free).
And, since the up-loader has a nice progress bar, then hitting cancel responds instant, and at all time the user is in a friendly way shown the progress of the uploading files.
In use, it looks like this:
While you can use the "select" to pop the file dialog, you can also use drag + drop to the hotspot like this:
Then, hitting Upload, then this:
So, I suggest adopting a great up-loading utility, and adding it to your "grab bag" of utilities for use in all of your applications.
I'm happy to post the working vb code used for the above up-loader example. You can find the ajaxtoolkit here:
https://learn.microsoft/en-us/aspnet/web-forms/overview/ajax-control-toolkit/getting-started/get-started-with-the-ajax-control-toolkit-cs#downloading-the-ajax-control-toolkit
I don't recommend trying to roll your own, since after boatloads of work, your result will be less then ideal compared to free pre-made up-loaders.
Edit: Setting up the AjaxToolkit
So, let's add the AJ toolkit using Nuget.
Hence, project->manage NuGet packages.
Hence this:
So, select the above package, and install it.
You should not have to now close the project, and re-open, but I suggest doing so.
Now, add this to web config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit" />
</handlers>
</system.webServer>
Note for above adding into web.config, if you "already" have a "system.webServer" section, then of course just add what's inside for above to the existing system.webServer tag/key in web.config.
So, at this point, then create a new test page.
And then from the tool box, drag + drop in the AjaxFileUpload
Ok, so now we have the uploader control.
You can use the property sheet, and choose the event that runs AFTER ONE file is uploaded. This event fires each time after a file upload (since you might have "many" files selected).
Hence, then this from the property sheet:
I assume we have a folder in the project for uploaded files, say UpLoadFiles.
Hence, this code stub should work:
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
' one file uploaded
Dim sSaveFile As String =
Server.MapPath("~\UpLoadFiles\" & e.FileName)
Debug.Print(sSaveFile)
AjaxFileUpload1.SaveAs(sSaveFile)
End Sub
本文标签: javascriptDrag and Drop files upload the RequestFilesCount is zeorStack Overflow
版权声明:本文标题:javascript - Drag and Drop files upload the Request.Files.Count is zeor - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744030636a2578842.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
[<>]
and provide a minimal reproducible example – mplungjan Commented Mar 28 at 15:41