I have an aspx page,where the user will enter a valid image url(ex : https://stackoverflow.com/Content/Img/stackoverflow-logo-250.png).
I need the program to upload this image to the Server.
How can i do this ?
System.Net.WebClient webClient = new WebClient();
webClient.DownloadFile(#"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png",
#"c:\path\localfile.png");
You can use Server.MapPath to get physical directory on the server corresponding to the relative or virtual path, for example Server.MapPath("~/Images")
Related
I have a scenario where the user passes a fileName to download.
We don't download the file on the server and stream back to the user because of bandwidth restrictions
We get the file path to download, and redirect to the location where the json file would be hosted
[Route("[controller]/DownloadJsonFile")]
public async Task DownloadJsonFile(string fileName)
{
//Get the file name
string fileToDownload = "https://hostedfilelocation/....test.json"
Response.Redirect(fileToDownload);
}
Currently, this method ends up rendering the Json content on the browser.
Is there a way so that the browser can start automatically downloading the file?
That way it wouldn't take super long to render the file on the browser.
P.S. If the file is of type zip or gzip, it is not rendered on the browser but rather is automatically downloaded.
The application is a .Net 6 Asp.Net MVC application
I have tried the below code but the behavior is the same but it renders json on the browser instead of downloading it.
string fileToDownload = "https://hostedfilelocation/....test.json"
HttpResponse response = HttpContext.Response;
response.Clear();
response.ContentType = "application/octet-stream";
response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
Response.Redirect(fileToDownload);
The approaches mentioned in this blog post are all mentioning rendering the file in an iframe but I want the download happen on the client side.
Download File via browser redirect
If you want to download it directly, add the download attribute:
<a class='download-file-link' target='_blank' href='DownloadJsonFile' download="somefilename">
Am trying to add an attachment to mail in asp.net VB.
I could send mail fine until I added the attachment code,
Dim attch As Attachment = New Attachment("http://sitehere.com/Documents/file.jpg")
mail.Attachments.Add(attch)
I am getting the error URI formats are not supported.
Any ideas why that is and what I can do about it?
The Attachment class expects either a path to a file on the file system, or a Stream.
Try:
Dim data As Byte() = New WebClient().DownloadData("http://sitehere.com/Documents/file.jpg")
Dim attachment As New Attachment(New MemoryStream(data), "file.jpg")
That's me doing my best to translate from C# to VB.NET so the syntax might not be 100% correct, but that's the general idea. That will download the data into a byte array, then create a memory stream from those bytes and pass that to the Attachment constructor.
You can't add an attachment straight from a URL. You'll need to download the file first, then add it as an attachment.
you can use HttpWebRequest to get the file as a stream, then attach the stream. That saves having to store the file on disk.
If you have the file locally in your server and in a folder which you know the path, dont use the uri for that,
Dim eMessage As New MailMessage
Dim attachLabel As Attachment
Dim location As String
loction= Server.MapPath("Documents\\file.jpg")
attachLabel = New Attachment(loction)
eMessage .Attachments.Add(attachLabel);
If you really want to send a file from another url, you may use HttpWebRequest to download that first and send it as Colin and Davy8 metnioned.
I am working on asp.net C# website in that I getting problem when I try to save image from remote URL.
I have tried with below c# code ...
// C# code
string remoteImageUrl= "http://www.bitpixels.com/getthumbnail?code=83306&url=http://live.indiatimes.com/default.cms?timesnow=1&size=200";
string strRealname = Path.GetFileName(remoteImageUrl);
string exts=Path.GetExtension(remoteImageUrl);
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImageUrl,Server.MapPath("~/upload/")+strRealname + exts);
When I fetch image from above remoteImageUrl then I getting error "An exception occurred during a WebClient request."
How can I fetch and save remote url image and store it my website upload directory.
or any other way to get remote url image.
I solved that problem The exception comes due to the extension..
When I getting extension of the remoteImageUrl Path.
string exts = Path.GetExtension(remoteImageUrl);
string strRealname = Path.GetFileName(remoteImageUrl);
It returns ".cms" so exception throws at that point,
I avoid the ".cms" extension from the remoteImageURL and then call
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImageUrl,Server.MapPath("~/upload/")+strRealname + exts);
It works fine.
Yout code is just fine. Make sure your application pool identity, has access to "upload" folder with write access.
And if you are using a proxy server you should also specify this in web.config file.
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>
</system.net>
Are you running under anything less than full trust? If so, you can't make arbitrary web requests either.
Let's say that I have my ASP.NET web application in a directory called "MyApp" both locally and on a remote server. I'm trying to build an onclick response to a link. The response calls a Javascript function, passing it the URL of an .aspx page in my web app. The Javascript pops out a new window displaying the page. My C# code looks like this:
link = new HyperLink();
link.Text = product_num_str;
link.NavigateUrl = "#";
string url = "Javascript:My_NewWindow('http://" +
HttpContext.Current.Request.Url.Authority +
"/ProductInfo.aspx?_num=" + product_num_str + "')";
link.Attributes.Add("onclick", url);
I started using the Request's Authority property because I was having problems running locally on the Visual Studio web server when I used the Host property. The problem was that Host only returned "localhost" instead of the host and port number.
When tested locally, the code works because the "authority" maps to my app root folder. The URL generated is, e.g.,
http://localhost:52071/ProductInfo.aspx?_num=123
If I run on a remote server, however, I end up with something like:
http://company-server/ProductInfo.aspx?_num=123
This fails to find the page, because in this case the "MyApp" root folder must be included.
There is probably an easier way - putting an entry in the web.config or something. My motivation originally was to allow the app to be published to a folder of any name and work as is.
I could hack my approach and search the string for "localhost" or something, but that's ugly. So how do I build a string that will work everywhere?
I'm assuming you're doing this from within a Page or Control. If that's the case you should do this instead:
string fullUrl = this.ResolveClientUrl("~/ProductInfo.aspx?_num=" + product_num_str + ");
That will give you the proper URL no matter where the application is deployed.
I'm trying to use an asp:FileUpload Control to allow users to upload files (.doc, .gif, .xls, .jpg) to a server that is outside of our DMZ and not the Web Server. We want to have the ability to look at these files for viruses, structure, etc prior to saving them into another directory that would allow access to outside users. From what I have read about this control is that it will allow for files to be uploaded to the web server. Can this control be used to upload files to a server other than the web server? If it can be done where should I look for this type of functionality or how do I force it to go to https:\servername\folder name (Where server name is not the web server)? Would I have to read the file then write it to the other server?
Thanks,
Erin
FileUoload control can only upload data to the web server. If you need to save file to a different server, you need handle the POST request, read data from the Fileupload control and save them to your UNC share.
As far I know, using the fileupload control you actually upload contents to webserver which inturn gets rendered to your client (page) when requested; I don't think you can upload files to different server other than webserver; that shouldn't happen as well. Take a look at the below URL for fileupload if you want
http://msdn.microsoft.com/en-us/library/aa479405.aspx
http://www.asp.net/data-access/tutorials/uploading-files-cs
Thanks.
This depends on your web server setting and permission granted to the application. If it is DMZ then I would assume that a very minimal permission is granted to the application. In such scenario the application will not be able to access any resource other than webserver unless an explicit permission is granted to the account running application to access the network resource (which is not recommended). However, if the nework server you are trying to save the file has ftp enabled, then you could write the bytes streamed in file upload control to the network server with authenticated ftp account that has necessary permission.
You may use the below function:
Imports System.Net
Imports System.IO
Public Function Upload(ByVal FileByte() As Byte, ByVal FileName As String, ByVal ftpUserID As String, ByVal ftpPassword As String, ByVal ftpURL As String) As Boolean
Dim retValue As Boolean = False
Try
Dim ftpFullPath As String = ftpURL + "/" + FileName
Dim ftp As FtpWebRequest = FtpWebRequest.Create(New Uri(ftpFullPath))
ftp.Credentials = New NetworkCredential(ftpUserID, ftpPassword)
ftp.KeepAlive = True
ftp.UseBinary = True
ftp.Method = WebRequestMethods.Ftp.UploadFile
Dim ftpStream As Stream = ftp.GetRequestStream()
ftpStream.Write(FileByte, 0, FileByte.Length)
ftpStream.Close()
ftpStream.Dispose()
retValue = True
Catch ex As Exception
Throw ex
End Try
Return retValue
End Function
Function Call:
Upload(FileUploadControl.FileBytes, "filename.ext" "user", "password", "ftppath")