ASP.NET MVC 3, pass the file from server to client - asp.net

Actually, this looks like the download feature, allowing a user to determine the local path where the file should be stored.
The whole thing is: the background program will generate a data file in the server, after that, I want to pass the data file from server to client.
I used FileStreamResult and FileContentResult, but it doesn't work.
A *.csv file was generated, then the file needs to transfer to the client. in controller , the code is very simple , like return new FilePathResult(filePath,"text/csv"); and I set the break point , the code execute without any exception , but I didn't see any web diaglog letting the user to select the path to save the csv file.

Try using return File()
public FileResult GetFile()
{
byte[] test = { 0 };
return File(test, "text/csv","TempFile.csv");
}
and calling it with an actionlink.
#Html.ActionLink("Download File","GetFile","Home")

Thank you guys, I changed the designe--place the csv file under the web root directory, (e.g. \File\Date\testing.csv) in the Controller method will return a json which point to the csv location (e.g. /File/Date/testing.csv) , the js should get the url and redirect to the /File/Date/testing.csv .
public FastJsonResult Download()
{
//generate the csv file under root path
//return the url point to the file
return JsonView(path);
}

Related

Where to store uploaded images in Linux server using Spring MVC

I have written a code to upload the images(profile picture of an student) in the server running in linux environment.The code is shown below
#RequestMapping(value = "/updatePhoto",method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("id") String id,
#RequestParam("file") MultipartFile file,
HttpServletRequest request,
Model model) throws IOException {
if(!file.isEmpty())
{
try
{
String relativePath="/resources";
String absolutePath=request.getServletContext().getRealPath(relativePath);
System.out.print(absolutePath);
byte[] bytes=file.getBytes();
File dir=new File(absolutePath);
if(!dir.exists())
{
dir.mkdir();
}
File uploadFile=new File(dir.getAbsolutePath()+File.separator+id+".jpg");
BufferedOutputStream outputStream=new BufferedOutputStream(new FileOutputStream(uploadFile));
outputStream.write(bytes);
outputStream.close();
model.addAttribute("uploadMessage","image uploaded for id"+id);
}
catch (Exception e)
{
System.out.print(e);
}
}
return "successFileUpload";
}
i have stored in "/resources" folder.but the problem is, whenever i generate the war file of whole application and deploy in server, it flushes the "/resources" folder and deletes the old uploaded images.Is there any way or the path ,i could upload the images.
The way I do is:
Create a directory in the server. For example: /myImages
Then grant full permissions for tomcat user
You are good to go now. I have read somewhere that you shouldn't save your stuff on /resources folder because it makes your app independent from container you are using: with tomcat you could use catalina.home but what if you shift to another container
I store the images inside my Tomcat home location as it will be outside of my project folder(war) and inside the tomcat.
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "images");
The above lines of code will create a folder in tomcat base directory with name 'images'.
This is the one of the best ways to store images.
Here's simple way
System.out.println(System.getProperty("user.dir"));

How to create ASP.NET websocket .ashx file's URL?

I am a newbie of Websocket. I have created a ASP.NET Web project in Visual Studio named CAPWebSocketProject. Inside this project there is a .ashx file named CPWebSocket.ashx. Inside this ashx file, there are c# codes. Here are the codes:
public class CPWebSocket : IHttpHandler
{
public long fnGetTerminalInfo()
{
string strCom = "COM4"; // hard coded for testing
string strGetTerminalInfoCommand = "C900";
<XXXX> clsTerminal = new <XXXX>();
long lgPortStat = clsTerminal.SendCommand(strCom, strGetTerminalInfoCommand);
return lgPortStat;
}
}
Now, my question is how to create the websocket CPWebSocket.ashx file's URL so I can access from a browser?
I don't think .ashx is websocket, you need to inherit from WebSocketService then you need to create object of websocket in javascript and give it the url of the websocket and the key want to listen to it, here's an example:
http://www.codeproject.com/Articles/1063910/WebSocket-Server-in-Csharp

Prevent access to file(s) to secure path based downloads

It is fairly common to allow users to download a file via having some path modifier in the URL
//MVC Action to download the correct file From our Content directory
public ActionResult GetFile(string name) {
string path = this.Server.MapPath("~/Content/" + name);
byte[] file = System.IO.File.ReadAllBytes(path);
return this.File(file, "html/text");
}
quoted from http://hugoware.net/blog/dude-for-real-encrypt-your-web-config
An application I'm working with has liberal path downloads ( directory based ) sprinkled throughout the application, hence it is super vulnerable to requests like "http://localhost:1100/Home/GetFile?name=../web.config" or ( ..%2fweb.config )
Is there an easy way to restrict access to the config file - do I need to provide a custom Server.MapPath with whitelisted directories - or is there a better way.
How do you secure your file downloads - are path based downloads inherently insecure?
A simple option, assuming that all files in the ~/Content directory are safe to download would be to verify that the path is actually under (or in) the ~/Content directory and not up from it, as ~/Content/../web.config would be. I might do something like this:
// MVC Action to download the correct file From our Content directory
public ActionResult GetFile(string name) {
// Safe path
var safePath = this.Server.MapPath("~/Content");
// Requested path
string path = this.Server.MapPath("~/Content/" + name);
// Make sure requested path is safe
if (!path.StartsWith(safePath))
// NOT SAFE! Do something here, like show an error message
// Read file and return it
byte[] file = System.IO.File.ReadAllBytes(path);
return this.File(file, "html/text");
}

Implement webdav for encrypted word document

I need to implement webdav in my application. So the user can edit word document, without need to download and back it upload to the server. However, the problem now, the document saved on webdav server are encrypted. Is it possible to use webdav for encrypted file?
Or another words, is it possible to make http-GET request to encrypted file
2080.enc (which actually encrypted word document)
[GET] /DAV/2016/02/2080.enc
and get a decrypted file word document as a response, so I can edit the word document? Many thanks
Regards
===============================================================
===============================================================
Here is actually the problem..
On the client side, I am going to download the document stored on webdav server like this
#item.GetDocumentActionTitle
<object id="winFirefoxPlugin" type="application/x-sharepoint" width="0" height="0" style="visibility: hidden;"></object>
<script>
function officelink(sDocumentUrl) {
$.get(sDocumentUrl, null, function (data) {
try {
new ActiveXObject("SharePoint.OpenDocuments.4").EditDocument(data);
return false;
}
catch (e) {
try {
document.getElementById("winFirefoxPlugin").EditDocument(data);
return false;
}
catch (e2) {
return true;
}
}
});
}
However, the url must be full path including domain name like this http://webdavserver.com/2016/02/2080.doc..
It work perfectly if it is a word document (2080.doc), however what actually stored in the server is NOT 2089.doc BUT 2080.sec (enrcypted word document)
If it is NOT word document, The function EditDocument wont be able to read the file. And later by saving the file, it must be encrypted as well
Can you understand my problem? What should I do?
Thanks

Attempting to open a user-specified file and process it, path is lost

So, I'm working on my first ASP.NET MVC 3 application and one thing I need to do is handle some data that is exported from someone else's system and turn around and import it, on user action, into the system and perform some error checking, etc. on it.
Here's how I have attempted to solve this issue:
I've got a view with a div:
<div>
<span><b>Recipe Data:</b>
<input type="file" name="uploadFile" />
<input type="submit" value="Load" />
</span>
</div>
and that allows me to choose a file and then submit it. Then I've got a controller action that looks like this:
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
try
{
// attempt to read the file
}
catch (Exception)
{
throw;
}
}
So, when I'm using IE, I can examine the uploadFile parameter and it gives me a path like:
FileName:c:\\Users\\Matt\\Desktop\\TestFiles\\AppleBerry.xml
(which is exactly the full path to the file I picked)
But when I try the same thing in FireFox, that path is stripped off, so uploadFile.FileName is just AppleBerry.xml and the XDocument.Load tries to load it from:
C:\Program Files (x86)\Common files\Microsoft Shared\DevServer\10.0\AppleBerry.xml
So, I'm pretty sure that I'm going about this the wrong way and need some guidance. I need to read in that XML file, preferably via XDocument.Load() and then do some checks and eventually push the records in that xml file into a DB table. The only part I'm having issues with is this file path. Any help you can provide with this would be most appreciated.
Try loading the file directly from the request stream and don't rely on the FileName property because you haven't saved the file on the server yet so it won't find it:
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
// attempt to read the file
var doc = XDocument.Load(uploadFile.InputStream);
// TODO: do something with the XML document
}
catch (Exception)
{
// Make sure you do something more meaningful here
// instead of rethrowing and erasing the stacktrace
throw;
}
}
else
{
// The user didn't upload any file => take respective actions
}
}
The server does not have access to the client's file system so the original path is irrelevant. Furthermore the file is not saved onto the server file system, so you should be loading it from the InputStream property, as per Darin's answer.

Resources