I'm trying to upload files with WebClient on network disc.
Everything is fine until I publish my app.
Code to upload:
public IFormFile Image{ get; set; }
(...)
imagename = FileHelper.GenerateFilename(Image.FileName);
var imgsave = Path.Combine(PathHelper.NewsFilePath, imagename);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
try
{
client.UploadFile(imgsave, Image.FileName);
}
catch (Exception e)
{
}
When I run application locally, it's working perfect, but when I publish my app, I get an error:
Error message: System.IO.FileNotFoundException: Could not find file 'C:\inetpub\wwwroot\application\test.PNG'.
File name: 'C:\inetpub\wwwroot\application\test.PNG' at (...)
Seems that published app is looking for this file somewhere within app folder. How can I indicate this file to upload it correctly?
Related
We're developing mobile application in Xamarin. How can next be accomplished in iOS:
user downloads file from url (http request is made to REST API, secured with Authentication Basic username:secretKey)
file is saved to iOS
user opens a file (allowed are jpg, png, pdf, doc, docx, png)
file is opened in default application (e.g. for images image viewer)
As file operations are platform specific, here's interface definition:
public interface IFileHelper
{
void DownloadFileAndSave(Models.DocumentModel document);
}
Android implementation:
public class FileHelper : IFileHelper
{
// download file and view status in download manager
public void DownloadFileAndSave(Models.DocumentModel document)
{
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Context.DownloadService);
string url = WebApiUtils.GetBaseUrl() + string.Format("Api/v1/Dms/{0}", document.UniqueId);
DownloadManager.Request request = new Android.App.DownloadManager.Request(Android.Net.Uri.Parse(url)));
request.AddRequestHeader("Authorization", "Basic " + WebApiUtils.GetEncodedCredentials(Auth.Users.Current));
var downloadFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
string path = Path.Combine(downloadFile.AbsolutePath, document.FileName);
request.SetDestinationUri(Android.Net.Uri.FromFile(new Java.IO.File(path)));
request.SetMimeType(document.ContentType);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
dm.Enqueue(request);
}
In Android file is simply stored on the filesystem and with File Explorer which is by default installed on any Android (i.e. My Files -> device storage -> Download), the file is opened in default application for file's mime type. Everything fine on Android.
Apple iOS implementation:
public class FileHelper : IFileHelper
{
public void DownloadFileAndSave(Models.DocumentModel document)
{
WebClient webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + WebApiUtils.GetEncodedCredentials(Auth.Users.Current));
webClient.DownloadDataAsync(new System.Uri(WebApiUtils.GetBaseUrl() + string.Format(Consts.ApiUrls.GetDocument, document.UniqueId)));
webClient.DownloadDataCompleted += (sender, e) =>
{
byte[] content = e.Result;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), document.FileName);
// doesn't throw exception therefore saved ok
File.WriteAllBytes(path, content);
Uri uri = new Uri(String.Format("file://{0}", path));
// doesn't work.
Device.OpenUri(uri);
};
}
}
Is there any other way to open downloaded file in default application. If I open url e.g. http://example.com/files/file1.png it opens the file in safari, but I can't put Authorization: Basic headers in Device.OpenUri.
I read about Load Non-Web Documents with WebView but you would have to build each file as BundleResource.
As Code Warrior commented there is one approach posted on link: https://forums.xamarin.com/discussion/36964/why-is-it-that-nothing-is-working-to-open-an-existing-local-pdf-file-in-the-ios-portion-of-my-pcl.
But Save image action doesn't work, everything else seems to work.
public void DownloadFileAndSave(Models.DocumentModel document)
{
WebClient webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + WebApiUtils.GetEncodedCredentials(Auth.Users.Current));
string tempPath = Path.GetTempPath();
string localFilename = Path.GetFileName(document.FileName);
string localPath = Path.Combine(tempPath, localFilename);
webClient.DownloadFileCompleted += (sender, e) =>
{
Device.BeginInvokeOnMainThread(() =>
{
QLPreviewItemFileSystem prevItem = new QLPreviewItemFileSystem(localFilename, localPath); // ql = quick look
QLPreviewController previewController = new QLPreviewController()
{
DataSource = new PreviewControllerDS(prevItem)
};
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(previewController, true, null);
});
};
// download file
Uri uri = new System.Uri(WebApiUtils.GetBaseUrl() + string.Format(Consts.ApiUrls.GetDocument, document.UniqueId));
webClient.DownloadFileAsync(uri, localPath);
}
When Save image is triggered I get next error:
2017-10-03 13:45:56.797 MyApp.iOS[477:61030] Video
/private/var/mobile/Containers/Data/Application/33D7139A-53E0-4A2E-8C78-D3D13A2259B0/tmp/water-h2o-md.png
cannot be saved to the saved photos album: Error
Domain=AVFoundationErrorDomain Code=-11828 "Cannot Open"
UserInfo={NSUnderlyingError=0x1c0445d60 {Error
Domain=NSOSStatusErrorDomain Code=-12847 "(null)"},
NSLocalizedFailureReason=This media format is not supported.,
NSURL=file:///private/var/mobile/Containers/Data/Application/33D7139A-53E0-4A2E-8C78-D3D13A2259B0/tmp/water-h2o-md.png,
NSLocalizedDescription=Cannot Open}
iOS treates image as video? Is this a bug on iOS or am I something missing.
UPDATE
It turns out that next permissions was missing in Info.plist file:
<key>NSPhotoLibraryUsageDescription</key>
<string>Application needs to access photos</string>
<!-- for iOS 11 -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Application needs to access photos</string>
Now Save Image action is working ok. But seriously Apple could return more appropriate error than Video image.jpg cannot be saved ...
I am following this article to upload and download files using silverlight child window.
http://gyansangrah.com/ArticleContent.aspx?ID=upload_and_download_file_in_lightswitch_2011
I am using 2013 though. I have referenced my download.aspx page in the lsxtproj file <_BuildFile Include="Server\Upload\Download.aspx">.
I can upload files no problems however when I download them I get a http 404 error.
It is trying to look for this URL.
http://localhost:54853/Client/Download.aspx?id=6
Requested URL: /Client/Download.aspx
I have my Download.aspx file in the server project and referenced it in my lsxtproj file.
I dont know why it will throw back http 404 error when trying to download the file using the command button.
Thanks
I Solve this problem by changing the Download_Execute() function by this;
partial void Download_Execute()
{
int fileId = this.FileCollection.SelectedItem.Id;
Uri hostUri = null;
Dispatchers.Main.Invoke(() =>
{
hostUri = System.Windows.Application.Current.Host.Source;
});
Dispatchers.Main.Invoke(() =>
{
UriBuilder myUri = new UriBuilder(hostUri.Scheme, hostUri.Host, hostUri.Port, "Download.aspx",
"?Id=" + fileId);
HtmlPage.Window.Navigate(myUri.Uri, "_new");
});
}
and changed the phrase in the lsxtproj file as this;
<_BuildFile Include="Download.aspx">
<SubFolder>
</SubFolder>
<PublishType>
</PublishType>
</_BuildFile>
I have a Web Api Application that performs a file upload to Amazon S3 when I POST a file path to it. How do I change the root directory this file path is relative to? Right now, if I send myVideo.flv as the file path, my app tries to find the file to upload at c:\windows\system32\inetsrv\myVideo.flv. I'd like it to look for the file at c:\MyApp\files\myVideo.flv. Is this something I change in the app config or iis?
Here is my controller method:
[HttpPost]
public HttpResponseMessage move([FromBody] Models.Request request)
{
string videopath = request.videopath;
try
{
PutObjectRequest putVideo = new PutObjectRequest
{
BucketName = WebApiConfig.AWSVideoBucket,
Key = videopath,
FilePath = videopath,
ContentType = "video/flv"
};
PutObjectResponse videoResponse = WebApiConfig.AWSclient.PutObject(putVideo);
if (videoResponse.HttpStatusCode == HttpStatusCode.OK)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
}
catch (FileNotFoundException e)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not found: " + e.Message);
}
}
Open IIS, Expand Sites and find your web site, Right click on the web site and select "Add Virtual Directory". This directory can be pointed to anywhere on the machine. In your app, you would read/write to this virtual directory under the root of the application. Also be mindful of permissions, to make sure the users accessing the site have proper permissions to that virtual directory.
I am developing a C# application which should connect to the user`s Dropbox using the DropNet C# Api.
I connect my application like this:
UserLogin login=client.GetToken();
client.UserLogin = login;
String url = client.BuildAuthorizeUrl();
ConnectForm authorizer = new ConnectForm(url);
authorizer.ShowDialog(this);
try
{
UserLogin accessToken = client.GetAccessToken();
this.toolStripStatusLabel1.Text = "connected";
}
catch (DropboxException exc)
{
client = new DropNetClient("API KEY", "API SECRET");
this.toolStripStatusLabel1.Text = "error";
}
My toolStripStatusLabel displays "connected" after this code part and after I try to upload a file (or to create a folder) like this
client.UploadFile("/", "test.txt", File.ReadAllBytes("C:/Users/Me/Desktop/test.txt"));
this.toolStripStatusLabel1.Text = "File uploaded";
it displays "File uploaded" but there are still no files in my Dropbox.. My Dropbox Api Error Log shows some 403 errors but without any further information.
Does anybody know whats wrong here?
I've found the solution.
When you register your application for "App-Folder" permission only you have to set client.useSandbox=true; directly after initalizing.
I am working on uploading files with a WCF web service,
here's my code for uploading:
public string UploadTransactionsFile(string uploadPath)
{
string uploadTransactionsFile;
if (String.IsNullOrEmpty(uploadPath))
return string.Empty;
if (!ValidateTransactionsFile(uploadPath))
return string.Empty;
try
{
var dir = #"C:\Upload\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadPath);
CheckDirectory(myUploadPath);
var client = new WebClient { Credentials = CredentialCache.DefaultCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadPath);
client.Dispose();
uploadTransactionsFile = "ok";
}
catch (Exception ex)
{
uploadTransactionsFile = ex.Message;
}
return uploadTransactionsFile;
}
I created a Windows Forms test client and added the service reference, but
my code in calling the method and hardcoded the file i want to upload:
private testServiceClient testService;
private void Button_Click(object sender, RoutedEventArgs e)
{
var File = "C:\\file.csv";
testService = new testServiceClient();
testService.UploadTransactionFile(File);
}
I can upload files using one computer, but when I put my test client to another computer, then I can't, because the file is just passing the stringpath, which cannot be found on server computer.
Am I missing something?
Do I have to send my file as byte[]? If so, then how do I do this?
To stream files over HTTP to WCF service:
http://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP
However, WebClient class is designed to be used on the client side too. So you could bypass the WCF service altogether.
From MSDN:
Provides common methods for sending data to and receiving data from a
resource identified by a URI.