DropzoneJs in Asp.net core application not uploading files - asp.net

I am trying to use DropzoneJS to upload multiple photos to a webapplication.
The Upload view contains following
<div class="jumbotron">
<form action="/Upload"
class="dropzone"
id="dropzoneJsForm"
style="background-color:#00BFFF"></form>
</div>
And the Upload controller contains this
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file, IHostingEnvironment _environment)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return RedirectToAction("Index");
}
When I run the application in debug mode and add files I see the progressbar and the checkmark indicating success. But no files has been uploaded in the upload folder in wwwroot.
I have app.UseStaticFiles() in the Configure method.
Target framework: .Net Core 2.0
I am using Visual Studio 2017 Professional latest version

<webconfig>
<system.web>
<httpRuntime maxRequestLength="15360" requestLengthDiskThreshold="15360"/>
</system.web>
'consider using fileupload='multiple' attribute on control

I found the mistake. A stupid beginner mistake. When I changed the name of the controller method to Index it worked.

Related

ASP.NET Core Convert byte array to svg image in a View

Using ASP.Net Core netcore 3.1 I have an SQL Server Table with a column of varbinary(MAX) with files uploaded into it. (Was done in ColdFusion) Now with the .Net core I want to display the svg images in the browser. Here is some more info:
In the Model class:
public byte[] FileContainer { get; set; } <-- this is the column with the file data
In the Controller it's just a simple:
List<TableName> userFiles = await _conn.TableName.Where(u => u.OwnerID == ID).ToListAsync();
return View(userFiles);
In the view:
#model IEnumerable<Projectname.Models.TableName>
…
#foreach (var item in Model){
<div style='width:12px;'>
#Html.Raw(item.FileContainer)
</div>
This just results in "System.Byte[]" being displayed in the browser. How do I make it display the svg file?
Add at the top of the View:
#using System.Text
Then do this:
#Html.Raw(Encoding.UTF8.GetString(item.FileContainer))
Works like a champ (tested in FireFox)

ASP .NET Publish Issue CS0103: The name 'Bundles' does not exist in the current context

I am trying to publish our website. It works fine on debug and release but publish gives me this error. We are using ASP .NET 4.0. I am using Visual Study 2013 for this project.
Error:
CS0103: The name 'Bundles' does not exist in the current context
Line 28: <meta name="viewport" content="width=device-width, initial-scale=1" />
Line 29: <%--<meta name="google-translate-customization" content="78033ccfddd8ecc6-eef53fe980f2236d-g873f5a559b682a69-a" />--%>
Line 30: <%=Bundles.RenderStylesheets()%>
Line 31:
Line 32: <script>
Web Config:
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Here is my config:
using Cassette;
using Cassette.Scripts;
using Cassette.Stylesheets;
using Cassette.BundleProcessing;
//using System.Web.Optimization;
namespace StudyXWebsite
{
/// <summary>
/// Configures the Cassette asset bundles for the web application.
/// </summary>
public class CassetteBundleConfiguration : IConfiguration<BundleCollection>
{
public void Configure(BundleCollection bundles)
{
// TODO: Configure your bundles here...
// Please read http://getcassette.net/documentation/configuration
// This default configuration treats each file as a separate 'bundle'.
// In production the content will be minified, but the files are not combined.
// So you probably want to tweak these defaults!
//bundles.AddPerIndividualFile<StylesheetBundle>("Content");
//bundles.AddPerIndividualFile<ScriptBundle>("Scripts");
bundles.Add<StylesheetBundle>("~/Styles/AllStyles.css");
bundles.Add<ScriptBundle>("~/Scripts/GGS.js");
bundles.Add<ScriptBundle>("~/Scripts/track.js");
// To combine files, try something like this instead:
// bundles.Add<StylesheetBundle>("Content");
// In production mode, all of ~/Content will be combined into a single bundle.
// If you want a bundle per folder, try this:
// bundles.AddPerSubDirectory<ScriptBundle>("Scripts");
// Each immediate sub-directory of ~/Scripts will be combined into its own bundle.
// This is useful when there are lots of scripts for different areas of the website.
}
}
}
Bin folder

Large file in Kendo UI Uploader

I want upload large file(600 MB) in ASP.Net Mvc with Kendo Uploader But I get flowing Exception:
OutOfMemoryException
Web.config: maxRequestLength and maxAllowedContentLength were set
before too
maxRequestLength = "2097152" maxAllowedContentLength = "2147483647"
Saeid is my coworker (really sharp man) and we solve the solution after a lot research,
so we think share it with you....
first of all
i want to describe solution.
we want to upload large file asynchronous with kendo ui upload widget but we have a problem.
when we upload large file (600MB or larger), application throw out of memory exception because application load 600MB to ram and .....
solution
1- if you want to use kendo ui uploader you must use following html code
<form method="post" enctype="multipart/form-data" action="api/UploadFile">
<input name="files" id="files" type="file" />
</form>
$("#files").kendoUpload({
async: {
saveUrl: "/api/UploadFile",
autoUpload: true
},
success: onSuccess,
upload: onUpload
});
1-1:you must use enctype="multipart/form-data" for async upload,
1-2:action="api/UploadFile" i want to upload file to UploadFile web Api
if you want use html input file,please you below html code
<form method="post" enctype="multipart/form-data" action="api/UploadFile">
<input name="files" id="files" type="file" />
</form>
2-Api must be has below code
public class UploadController : ApiController
{
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (Request.Content.IsMimeMultipartContent() == false)
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (MultipartFileData file in provider.FileData)
{
string directory = Path.GetDirectoryName(file.LocalFileName);
string filename = file.Headers.ContentDisposition.FileName.Replace(#"\","").Replace(#"""","");
File.Move(file.LocalFileName, Path.Combine(directory, filename));
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
}
2-1 : we determind app_data folder to save uploaded file
Now you can upload file Async but if you choose large file then you get out of memory exception
for resolve this problem ,you should say to mvc to not buffer data in UploadFile Api.
it has easy solution
Please Read following Article for solve it.
Dealing with large file

How to load images to page from image folder dynamically

I'm using MVC4 c#. I'm trying to load images that I need to show on a page dynamically by reading the content of the image folder and doing a foreach loop. I'm not sure how to read the content of the folder which is called ImageFiles which is located in the project and not the c:\ of the server. This is what I used and it works on my local computer but when I use ../../filename/filename/ImageFiles as the path it does not work. Can anyone help?
string filePath = #"../../Content/EventFiles/ImageFiles";
DirectoryInfo directory = new DirectoryInfo(filePath);
#foreach (FileInfo file in directory.GetFiles())
{
<\a href="../../Content/EventFiles/ImageFiles/#file.Name">
<\img src="/Content/EventFiles/ImageFiles/#file.Name" />
<\/a>
}
You are not referencing the filePath correctly.
Try this one on your View..
#{DirectoryInfo dir = new DirectoryInfo(Server.MapPath(Url.Content("~/Content/EventFiles/ImageFiles")));}
#foreach (var file in dir.GetFiles())
{
<img src="#Url.Content("~/Content/EventFiles/ImageFiles/" + file.Name)" />
}
Answer is Server.MapPath(). For desktop applications DirectoryInfo() works but for a web application I had to use Server.MapPath().
Thanks

How can I render Razor page from Assembly

UPDATE1
I've added RazorGenerator and etc...
After set custom tools, I've seen generated code for my razor pages.
Added this code in assembly
public class MyAreaRegistration : AreaRegistration
{
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Dictionary_default", "MyDictionary/{Action}/", new { controller = "DictionaryControllerBase", action = "Index" });
}
public override string AreaName
{
get { return "MyDictionary"; }
}
#endregion
}
But when I open page by url /MyDictionary, i see "Unable to find the resource."
NOTE I use in my project MVC3 and Spring.Net
I use one controller (base controller) in another Assembly with razor pages.
In my project I make controller inherited from base controller, just it make some settings. But razor pages I wish to use from assembly.
How can I do it?
You could the RazorGenerator extension. I have detailed how this can be achieved in the following post. The idea is that the RazorGenerator extension would create a corresponding .cs file for each Razor view and it will update it every-time you make a change to the corresponding view. This way the Razor views will be precompiled in the class library along with their respective controllers and view models. The RazorGenerator.Mvc NuGet will then register a custom virtual path provider which will take care of resolving those views.

Resources