how to set the save location in run time in mvc application - asp.net-mvc

I need to set the save location in run time in mvc application . In windows appication we use the
System.Windows.Forms.SaveFileDialog();
But, what we use the web Application?

It is not clear what you want to save. In a web application you could use the file input to upload files to the server:
<input type="file" name="file" />
For more information about uploading files in an ASP.NET MVC application you may take a look at the following post.
If on the other hand you want the user to be able to download some file from the server and prompted for the location where he wants to save this file you could return a File result from a controller action and specify the MIME type and filename:
public ActionResult Download()
{
var file = Server.MapPath("~/App_Data/foo.txt");\
return File(file, "text/plain", "foo.txt");
}
There are also other overloads of the File method that allow you to dynamically generate a file and pass it as a stream to the client. But the important part to understand in a web application when downloading a file from a server is the Content-Disposition header. It has 2 possible values: inline and attachment. For example with the above code the following header will be added to the response:
Content-Type: text/plain
Content-Disposition: attachment; filename=foo.txt
... contents of the file ...
When the browser receives this response from the server it will prompt the user with a Save As dialog allowing him to choose the location on his computer to store the downloaded file.
UPDATE:
Here's how you could achieve similar in a web application:
public ActionResult Download()
{
var file1 = File.ReadAllLines(Firstfilpath);
var file2 = File.ReadAllLines(2ndfilpath);
var mergedFile = string.Concat(file1, file2);
return File(mergedFile, "text/plain", "result.txt");
}

Related

.net core 2 rejects request with 415 when I set Accept to text/csv

When i POST a request to my .net core 2 mvc backend it returns json data.
I want to optionally change the headers as so , which i will then return a csv file of the data for download
'Accept': 'text/csv',
'Content-Type': `text/csv; charset=utf-8`
I set the controller base class with this Produces filter
[Produces("application/json", "text/csv")]
But those headers always cause .net to return 415 Unsupported Media Type
The controller action looks like this
[HttpPost]
public async Task<IActionResult> Post([FromBody] PostArgs args)
You source of problem is Content-Type: text/csv; charset=utf-8 header.
[FromBody] forces MVC middleware to use the input formatter for model binding (I am talking about PostArgs model). And by default, ASP.NET Core registers only one, JSON input formatter. Cause you set Content-Type, middleware cannot use that default formatter (as Content-Type header says that data in request body should be processed as CSV, not JSON) and so it throws 415 Unsupported Media Type error.
... I want to optionally change the headers as so , which i will then return a csv file of the data for download
Actually, it looks like you understand in wrong way what Content-Type header does:
In requests, (such as POST or PUT), the client tells the server what type of data is actually sent.
In other words, you only need to specify the Accept header, cause
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals.
And it is the server then, who uses a Content-Type header in responses to tell the client what the content type of the returned content (in response) actually is.
To return csv data, you return a ContentResult rather than a JsonResult object. This allows you to define the Content-Type:
return new ContentResult("csv-data", "text/csv", 200);
If you want to return a physical file you could return a FileResult object.
By default, the Accepts header isn't enforced. You can enforce it via configuration:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
});
In order to accept additional formats, you'll also need to add InputFormatters:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new TextInputFormatter())
config.OutputFormatters.Add(new StringOutputFormatter());
});

How to get Edge to inline open a PDF from MVC Redirect

I have a Microsoft MVC 4 application that needs to open a PDF file served from another MVC application. The code in the main application looks like this:
return Redirect(model.PdfUrl);
where model.PdfUrl looks like http://repository.{domain_name}/pdf/whitepaper/810219c9-a599-4132-965a-d3388d0fce3e.pdf
On the repository application, this request is routed to a controller action that looks-up the actual file from the incoming URL. Once the physical path of the file has been found, it returns the file to the HTTP Response as follows:
var mimeType = MimeMapping.GetMimeMapping(path);
return File(path, mimeType);
Using Fiddler, this creates the following response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/pdf
Date: Thu, 26 May 2016 16:16:07 GMT
Content-Length: 582158
Chrome, Firefox, Internet Explorer 11, all then open and render the PDF file 'inline'. Microsoft Edge however, displays a prompt asking if you want to download the file - at least it does most of the time, though sometimes it just opens the file as expected/required.
I have tried adding a content-disposition header to the response, but it does not appear to make any difference.
var mimeType = MimeMapping.GetMimeMapping(path);
var cd = new ContentDisposition
{
Inline = true,
FileName = Path.GetFileName(path)
};
Response.AddHeader("Content-Disposition", cd.ToString());
return File(path, mimeType);
Any ideas or suggestions would be much appreciated.

How to allow download just .zip and exe [Laravel 5.1]

How can I allow that user be able just to download zip and exe files?
I am currently use this function:
public function download($id)
{
$headers = array(
'Content-Type: application/x-msdownload',
'Content-Type: application/zip'
);
return response()->download(storage_path() . '/app/' . 'gamers.png', 'gamers.png', $headers);
}
And this allow me download any file, how can I limit it just on zip and exe?
You are trying to send a response so the headers mean only that browser will understand you are sending a file of type Content-Type application/x-msdownload or application/zip. To limit the files from server directly you can try limiting the directory using .htaccess file and in the code you get the $id probably you could get the file object or details of the file(if you have any) and check its type before sending the response.
Example for limiting access to files in folder with extension
Deny access to specific file types in specific directory
you can customize the above as per your needs

Is it possible to compose URL that forces browser to download file instead of play it?

Let say we have some file at http://somedomain.com/somedir/file.mp4.
When I send such URL to someone, I would like that browser start download, not play automatically.
Is it possible to compose URL in such manner to give browser instruction to start download instead of play it? With some parameter included maybe?
You can't do that by just sending the URL to someone.
What you can do is create a simple file which forces the user to download the file by setting the mime type of the response to octet/stream, which is the way of telling the browser the file can not embedded.
Below is an example in PHP taken from this website.
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

XML file generation to user specified location

I am generating a xml file using JAXB but at present file is generated at specified location,How can i use a browse button to specify the location of folder to save the generated file.
Have tried with input type="file" of HTML but it is useful for uploading the file.Want it to do from rich faces only.
Just write it directly to the HTTP response along with a Content-Disposition header with a value of attachment. This will force the browser to pop a Save As dialogue.
So, essentially all you need to do is to marshal the XML tree straight to the output stream of the HTTP response instead of the output stream of the file after having set the proper headers.
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// ...
ec.responseReset(); // Make sure the response is clean and crisp.
ec.setResponseContentType("text/xml"); // Tell browser which application to associate with obtained response.
ec.setResponseCharacterEncoding("UTF-8"); // Tell browser how to decode the characters in obtanied response.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // Tell browser to pop "Save As" dialogue to save obtained response on disk.
marshaller.marshal(model, ec.getResponseOutputStream()); // Look ma, just marshal JAXB model straight to the response body!
fc.responseComplete(); // Tell JSF that we've already handled the response ourselves so that it doesn't need to navigate.
Note: downloading a file via ajax is not possible. Remember to turn off the ajax feature of the RichFaces/Ajax4jsf command component invoking this method, if any.
See also:
How to provide a file download from a JSF backing bean?

Resources