XMLHttpRequest content-disposition null issue - javascript

This is my controller.
[HttpGet("GetFile")]
[Authorize]
public async Task<FileContentResult> GetFile([FromQuery] Guid fileId)
{
var fileName = string.Format("{0}.doc", _service.GetFileNameFromId(fileId));
var fileName = "someFile.doc";
var mimeType = "application/msword";
byte[] fileBytes = _service.GetFileByteArray(fileId);
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
These are my response headers according to Swagger.
content-disposition: attachment; filename="someFile.doc"; filename*=UTF-8''someFile.doc
content-length: 3853
content-type: application/msword
date: Thu31 Mar 2022 13:05:34 GMT
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
But whenever I attempt to access the content-disposition header from Javascript, it returns null. I'm making an XMLHttpRequest.
var contentDisposition = this.getResponseHeader('content-disposition');
Does my server-side code have any issues that could be causing this?

Below is my work Post demo, you can refer to it.
FileAPIController.cs:
[Route("api/[controller]")]
[ApiController]
public class FileAPIController : ControllerBase
{
private IWebHostEnvironment webHostEnvironment;
public FileAPIController(IWebHostEnvironment _webHostEnvironment)
{
webHostEnvironment = _webHostEnvironment;
}
[HttpPost("UploadFile")]
public async Task<string> UploadFile([FromForm] IFormFile file)
{
string path = Path.Combine(this.webHostEnvironment.WebRootPath, "IFiles/", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = file.FileName,
Inline = false
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return "https://localhost:5001/IFiles/" + file.FileName;
}
}
Privacy.cshtml:
#{
ViewData["Title"] = "Privacy Policy";
}
<h1>#ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<input type="file" id="File" />
<button id="AddButton" onclick="UploadFile()" type="submit">Add</button>
<script type="text/javascript">
function UploadFile() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://localhost:5001/api/FileAPI/UploadFile", true);
data = new FormData();
data.append("file", document.getElementById("File").files[0]);
xhttp.send(data);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var disposition =xhttp.getResponseHeader('Content-Disposition');
alert(this.response);
}
};
}
</script>
Result:

Related

Send blob file from javascript to C# asp.net

Hi I have a problem when I send a blob file from client side to backend. The website is in C# web forms.
the code of javascript:
function (data) {
console.log(data.buffer);
window.open(URL.createObjectURL(new Blob([data.buffer], { type: 'application/pdf' }), "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10"));
PostBack(data);
<%-- $.unblockUI();--%>
delete data;
},
The POSTBACK function:
function PostBack(data) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.status);
console.log("staturi");
console.log(data);
// Typical action to be performed when the document is ready:
/*document.getElementById("MainContent_Label2").innerHTML = xhttp.responseText;*/
}
};
xhttp.open("POST", '<%= ResolveUrl("Default.aspx/testSS") %>', true);
xhttp.send(data);
}
Can you help me recive the PDF file and save it to server folder.
The backend function:
[WebMethod]
public string testSS(byte[] fileContent)
{
string straudioPath = "~App_Data/";;
FileStream objfilestream = new FileStream(straudioPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(fileContent, 0, fileContent.Length);
objfilestream.Close();
return "OK";
}
Thank you for your help in advanced.

C# - Sending a XML over to Action result via JavaScript in cshtml

I have a .cshtml file which contains JavaScript function to perform a POST action to my controller class.
<input type="text" placeholder="Username" id="username" />
<button type="submit" onclick="sendResult()">Submit</button>
<script type="text/javascript">
function sendResult() {
let username = document.getElementById('username').value;
try {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test/Test");
xmlhttp.setRequestHeader('Content-Type', 'text/html');
let xml = `<?xml version="1.0"?><query><Username>${username}</Username></query>`;
console.log(xml)
xmlhttp.send(xml);
let xmlResponse;
xmlhttp.onreadystatechange = async function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
xmlResponse = await xmlhttp.responseXML;
console.log(xmlResponse)
}
}
} catch (error) {
console.log(error)
}
}
</script>
In my controller class, I did not manage to receive the xml string (myXML) after clicking on the submit button. Why is that so?
// TestController.cs
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(string myXML)
{
Service1Client o = new Service1Client();
o.Test(myXML);
return View();
}

How to display a message after downloading a file using XMLHttpRequest?

Hello community I hope you can help me since I could not show a message to the user after downloading an excel file.
I am using httpRequest for sending data to the server and everything works correctly the file is downloaded but what I also want is to show the message.
Thank you very much for your help.
This is my code javaScript.
function download_excel_file() {
var file_name; //Example Test.xlsx
var parameter = '{file_name:"' + file_name + '"}';
var url = "Download.aspx/Download_File";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
var a;
if (xhr.readyState === 4 && xhr.status === 200) {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = file_name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Here I want to show the message with the legend = File downloaded successfully but it does not work.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = 'blob';
xhr.send(parameter);
}
<input id="btn_download_file" type="button" value="Download file" class="btn btn-success btn-block" onclick="return download_excel_file();"/>
<div id="message_download" class="p-3 mb-1 bg-secondary text-white text-center" style="display:none"> </div>
This is my code from server.
[WebMethod]
public static void Download_File(string file_name)
{
if (file_name != null || file_name != "")
{
string path = HttpContext.Current.Server.MapPath("~/Folder_Excel/" + file_name);
if (File.Exists(path))
{
// This is the message I want to show in the div $("[id*=message_download]")
HttpContext.Current.Response.Write("File downloaded successfully");
System.IO.FileStream fs = null;
fs = System.IO.File.Open(path, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + file_name);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.Write("No files");
}
}
}
Add an ‘alert’ at the end of the script:
<script>
function myFunction() {
alert("Success! File downloaded!");
}
</script>
added 2019 10 04
Use InnerHTML along with getElementById to set the message back from the server.
from https://www.w3schools.com/xml/xml_http.asp
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
You should display your message at first, then make the browser "click" on the download button. Otherwise the browser may just fire an unload event and stop executing any scripts at this time - like on redirection.
I don't think you're using the Attribute Contains Selector correctly.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
Try this instead:
$("[id*='message_download']").css("display","block");
$("[id*='message_download']").text(xhr.responseText);
Or better yet, use $("#message_download") Also notice that I changed xhr.response.Text to xhr.responseText

white label error when i generate pdf

I use spring boot and I use this code to generate pdf document.
#GetMapping(value = "/members/{memberId}/contract/{contractId}/generalcontracts", produces = "application/pdf")
public ResponseEntity<byte[]> getMemberContract(#PathVariable("memberId") Long memberId, #PathVariable("contractId") Long contractId) throws IOException {
byte[] content = reportService.generateMemberContractReport(contractId);
return prepareReport(content);
}
private ResponseEntity<byte[]> prepareReport(byte[] content) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "report.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
In js, I do
<button id="memberPrintReport" type="button" class="btn btn-primary">Imprimer</button>
$("#memberPrintReport").on('click', function (e) {
tryit(getHostName() + "/members/" + memberId + "/contract/" + contractId + "/generalcontracts");
}
function tryit(urlServer) {
var win = window.open('_blank');
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
}
A new tab open, I see during a few second a white label error and after I see the pdf.
I don't understand why I get during a few instant this white label error
Image of the white label error
https://imagebin.ca/v/3Wnqxfpq1yR6
edit:
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "Basic " + $.cookie('authorization'));
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success)
success(xhr.response);
}
};
xhr.send(null);
}
Edit
that work with chrome, but not with firefox
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url, '_blank');
});
}
Your are executing this line: var win = window.open('_blank'); which result in opening http://localhost:8080/_blank, as javascript understand _blank as url. so you need to update your tryit function to this:
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url,'_blank');
});
}

how to add parameter into HttpContext.Request.Form from client side

I wanted to know how to add parameters into HttpContext.Request.Form via client side so that in the serve side i can get these data
i don't want to use ajax.
I tried the following but with no success:
javascript code:
var request = new XMLHttpRequest();
request.open("POST", window.location.host, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.append('skip', '10');
request.send(formData);
the asp.net mvc line of code:
var a = HttpContext.Request.Form.GetValues("skip");
but a is equal to null.
thank you all
Update:
I want to do something like datatable. In datatbles you can set draw,start, col_order etc. And you can get it with request into the server side. I want to know how can i do something like that.
You will need to combine data like this - "key1=value1&key2=value2&skip=10".
View
<button type="button" onclick="postData()">Post data</button>
<div id="result"></div>
<script>
function postData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("POST", "#Url.Action("PostData", "Home")", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2&skip=10");
}
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult PostData(FormCollection collection)
{
var key1 = collection["key1"];
var key2 = collection["key2"];
var skip = collection["skip"];
return Json($"key1: {key1}, key2: {key2}, skip: {skip}");
}
}
Screen Shots

Categories

Resources