C
C#•11mo ago
Ketamine Kyle

ASP.NET How to return a view and filecontents

I CANT FIGURE THIS OUT MAN WHAT THE HELL Current code
[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
try
{
DragonSim.Builder.Build.Compile(bvm);
var filePath = Path.Combine(Paths.BuildPath, bvm.Filename + ".bat");
var fileBytes = System.IO.File.ReadAllBytes(filePath);
var fileContentResult = File(fileBytes, "application/octet-stream", bvm.Filename + ".bat");

return Json(new { success = true, message = "Build successful", fileContent = Convert.ToBase64String(fileBytes) });
}
catch (Exception ex)
{
return Json(new { success = false, message = "Error building stub: " + ex.Message });
}
finally
{
System.IO.File.Delete(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat"));
System.IO.File.Delete(Path.Combine(Paths.BuildPath, "DragonSim.exe"));
}
}
[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
try
{
DragonSim.Builder.Build.Compile(bvm);
var filePath = Path.Combine(Paths.BuildPath, bvm.Filename + ".bat");
var fileBytes = System.IO.File.ReadAllBytes(filePath);
var fileContentResult = File(fileBytes, "application/octet-stream", bvm.Filename + ".bat");

return Json(new { success = true, message = "Build successful", fileContent = Convert.ToBase64String(fileBytes) });
}
catch (Exception ex)
{
return Json(new { success = false, message = "Error building stub: " + ex.Message });
}
finally
{
System.IO.File.Delete(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat"));
System.IO.File.Delete(Path.Combine(Paths.BuildPath, "DragonSim.exe"));
}
}
30 Replies
Ketamine Kyle
Ketamine KyleOP•11mo ago
<script>
function buildStub() {
var formData = $('#builderForm').serialize();

$.ajax({
url: '/Builder/ZaBuildor',
type: 'POST',
data: formData,
success: function (response) {
if (response.success) {
alert(response.message);


var blob = b64toBlob(response.fileContent, 'application/octet-stream');
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'DragonSim.bat';
link.click();
} else {
alert('Error building stub: ' + response.message);
}
},
error: function (error) {
alert('Error building stub: ' + error.responseText);
}
});
}

function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;

var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);

var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
</script>
<script>
function buildStub() {
var formData = $('#builderForm').serialize();

$.ajax({
url: '/Builder/ZaBuildor',
type: 'POST',
data: formData,
success: function (response) {
if (response.success) {
alert(response.message);


var blob = b64toBlob(response.fileContent, 'application/octet-stream');
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'DragonSim.bat';
link.click();
} else {
alert('Error building stub: ' + response.message);
}
},
error: function (error) {
alert('Error building stub: ' + error.responseText);
}
});
}

function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;

var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);

var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
</script>
The html is just a basic form with a button BUT IT JUST CLOSES THE DAMN PROCESS CUZ IM NOT RETURNING THE VIEW 😭
alex
alex•11mo ago
first of all why are you using jquery
Ketamine Kyle
Ketamine KyleOP•11mo ago
What should I do that would be better
alex
alex•11mo ago
second of all what exactly are you trying to do not jquery because its obsolete
Ketamine Kyle
Ketamine KyleOP•11mo ago
So I have a download button and it sends the form data to my controlller and it compiles a application then im trying to send the filecontents back to the user so they can download it but the problem im having is when I download it the program just closes because there is no view to return to im guessing> But it just closes the program after its downloaded
alex
alex•11mo ago
why are you returning JSON instead of simply returning a file stream
Ketamine Kyle
Ketamine KyleOP•11mo ago
I did that already did not work That code is chat gpt mostly my code was different but I resorted to gpt after none of my attempts worked at all
[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
DragonSim.Builder.Build.Compile(bvm);
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}
[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
DragonSim.Builder.Build.Compile(bvm);
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}
alex
alex•11mo ago
thats how i would do it. i dont know how that works with an ajax call but what you could do is POST a form with target=_blank to download the file
Ketamine Kyle
Ketamine KyleOP•11mo ago
Well I was calling the controller like this
<form asp-controller="Builder" asp-action="ZaBuildor" method="post">
<form asp-controller="Builder" asp-action="ZaBuildor" method="post">
Aand the program just dies and exits after Ive downloaded the file
alex
alex•11mo ago
define dies and exits
Ketamine Kyle
Ketamine KyleOP•11mo ago
The program closes
Ketamine Kyle
Ketamine KyleOP•11mo ago
No description
Ketamine Kyle
Ketamine KyleOP•11mo ago
It just exits After I download the file
alex
alex•11mo ago
i dont think its supposed to do that
Ketamine Kyle
Ketamine KyleOP•11mo ago
uh yeah 😭 I tried that it opens a new tab right? then opens the save dialog box program is open still at this point Then then then I press save and it just closes Like what
alex
alex•11mo ago
put a breakpoint and step through
Ketamine Kyle
Ketamine KyleOP•11mo ago
alright but im sure it just dies once it returns the file since im not returning a view I have to figure out how to return the file contents and the view cuz rn its returning the file contents but then it has no view to return to and it just closes that is my theory
alex
alex•11mo ago
i doubt that
Ketamine Kyle
Ketamine KyleOP•11mo ago
Well I cannot step through html code
alex
alex•11mo ago
is it an api route or a page route? the server code
Ketamine Kyle
Ketamine KyleOP•11mo ago
It works fine I already stepped through It returns the file just fine thats why I can download the file
public class BuilderController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Builder()
{
return RedirectToAction("Index");
}

[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
DragonSim.Builder.Build.Compile(bvm);
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}

}
public class BuilderController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Builder()
{
return RedirectToAction("Index");
}

[HttpPost]
[Route("Builder/ZaBuildor")]
public IActionResult Build(BuilderViewModel bvm)
{
DragonSim.Builder.Build.Compile(bvm);
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}

}
It does not work when it is a API route it says "Invalid Type"
type "https://tools.ietf.org/html/rfc7231#section-6.5.13"
title "Unsupported Media Type"
status 415
type "https://tools.ietf.org/html/rfc7231#section-6.5.13"
title "Unsupported Media Type"
status 415
this is what happens if i put it asa Api route
alex
alex•11mo ago
to fix that you probably need to specify the accepted types for post body
✿ Scarlet ✿
✿ Scarlet ✿•11mo ago
Ok so, the idea is:
public class MyController : Controller
{
public IActionResult Index()
{
return View();
}

[HttpGet("someFileContent")]
public IActionResult SomeFileContent()
{
(...)
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}
}
public class MyController : Controller
{
public IActionResult Index()
{
return View();
}

[HttpGet("someFileContent")]
public IActionResult SomeFileContent()
{
(...)
var fileContentResult = File(System.IO.File.ReadAllBytes(Path.Combine(Paths.BuildPath, bvm.Filename + ".bat")),
"application/octet-stream", bvm.Filename + ".bat");

return fileContentResult;
}
}
In your view:
<script>
function download(dataurl, filename) {
var a = document.createElement("a");
a.href = dataurl;
a.setAttribute("download", filename);
a.click();
return false;
}

download("application/octet-stream,someFileContent", "/");
</script>
<script>
function download(dataurl, filename) {
var a = document.createElement("a");
a.href = dataurl;
a.setAttribute("download", filename);
a.click();
return false;
}

download("application/octet-stream,someFileContent", "/");
</script>
@Ketamine Kyle
alex
alex•11mo ago
var NOOO
✿ Scarlet ✿
✿ Scarlet ✿•11mo ago
This code is from stack overflow I just adapted it to the current context
Ketamine Kyle
Ketamine KyleOP•11mo ago
Yeah im doing something similar if mine does not work ill use this thanks so much Tryna get this done so I can get started on my college revision 🤣
✿ Scarlet ✿
✿ Scarlet ✿•11mo ago
actually you could just use in the view:
<script>
window.open("/someFileContent");
</script>
<script>
window.open("/someFileContent");
</script>
Ketamine Kyle
Ketamine KyleOP•11mo ago
Well each user is going to have a different file path based on what they inputted in the text box on the form so im gonna have to make it get the formdata also should be easy tho Still just closes So confusing what in the fuck man Think I fucked up the code somewhere I had to make alot of changes cuz I have to pass formdata through
function build() {
const formData = new FormData(document.getElementById('buildStubForm'));
fetch('/Download/ZaBuildor', {
method: 'POST',
body: formData
})
.then(response => response.blob())
.then(blob => {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'test.bat';
link.click();
});
}
function build() {
const formData = new FormData(document.getElementById('buildStubForm'));
fetch('/Download/ZaBuildor', {
method: 'POST',
body: formData
})
.then(response => response.blob())
.then(blob => {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'test.bat';
link.click();
});
}
Like it starts the download and when I press save it instantly closes the program like instantly like before
Ketamine Kyle
Ketamine KyleOP•11mo ago
It gets too here then when I press save file and it downloads the program exits
No description
Ketamine Kyle
Ketamine KyleOP•11mo ago
How does that even make sense
Want results from more Discord servers?
Add your server