I have created an MVC ASP.Net application and hosted in within IIS. Part of my app allows for users to upload a csv file. The data then needs to be read out of the csv and into an object to be used elsewhere.
The problem I have is when hosted in IIS the file can not be read. Here is my code:
using (StreamReader CsvReader = new StreamReader(filePath))
{
MessageHandler.NewNote("Opened CSV Reader");
string inputLine = "";
int lineNumber = 0;
while ((inputLine = CsvReader.ReadLine()) != null && !string.IsNullOrEmpty(inputLine))
{
//Do something here
}
}
Can someone please advise how I get this working. The filepath is generated using the following upload form:
<div id="UploadForm">
<% using (Html.BeginForm("FileUpload", "ImportExport", Model,
FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input name="uploadFile" type="file" accept=".csv" style="width:70%;" />
<input type="submit" value="Upload File" />
<%} %>
</div>
The filePath is coming from the client, there should be no file existing on the server at the given file path.
You need to read the data from the Stream coming from the upload form instead of the file path.
Please refer to the following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx
Related
I am having an unusual issue when I deploy my code from VS2015 to IIS. In VS when I run the web code, either as debug or release, the image I select and load then convert to base64 is converted to a byte array and saved to the database without any problems. However, when I deploy to the web server the code fails to work and the image is never updated. I am not getting any error information. As long as I run it from VS it all works. Is there something on the IIS server that needs to be configured? Any help or comments will be greatly appreciated.
HTML CODE
<form class="input-group" id="img2b64">
<input id="inputFileToLoad" name="files" type="file"
onchange="encodeImageFileAsURL();" />
</form>
<!-- is used to display b64 code and hold the b64 for ajax call to controller -->
<textarea id="b64" class="form-control"></textarea>
JQUERY CODE
function encodeImageFileAsURL(cb) {
return function () {
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function () {
cb(reader.result);
}
reader.readAsDataURL(file);
}
}
$('#inputFileToLoad').change(encodeImageFileAsURL(function (base64Img) {
$('#act_Photo').attr('src', base64Img);
$('#b64').val(base64Img);
}));
IN THE CONTROLLER CODE
// model.ImageFile is the base64 string
if (!string.IsNullOrEmpty(model.ImageFile))
{
// strip out base64 header
int pos = model.ImageFile.LastIndexOf(',') + 1;
string data = model.ImageFile.Substring(pos);
// get byte array of base64 image
byte[] bytes = Convert.FromBase64String(data);
// convert and save as byte array to DB
var acctImg = new WebImage(bytes).Resize(220, 200, false, true);
// aRec.Photo is in DB record
aRec.Photo = acctImg.GetBytes();
}
Seems like all is well. I restarted the site in IIS. Seems to have been a caching issue causing all the grief. Sometimes I just hate caching.
I am using the fast-csv packaged for Meteor installed:
meteor add chhib:fast-csv
My app is only able to open up a csv file "my.csv" at a predetermined location. The problem is it doesn't allow me to choose any other file. Find below my code:
client/main.js
var stream = fs.createReadStream("my.csv");
var csvStream = csv()
.on("data", function(data){
console.log(data);
})
.on("end", function(){
console.log("done");
});
stream.pipe(csvStream);
I would like to redesign the app so that I am able to read/upload a csv file of my choice, via an File Upload button.
Find below my File Upload Button html code:
client/main.html
<input type="file" id="myFile">
How do I get the contents uploaded from the File uploaded button into the stream variable?
var stream = fs.createReadStream("uploaded file");
You can use simply js FileReader for reading the contents of uploaded file.
Add below code in your file upload event handler :
var file = document.getElementById("myFile").files[0];
var reader = new FileReader();
reader.onload = function(fileLoadEvent) {
// file contents are available in reader.result
var stream = reader.result; // saving file contents in stream variable
};
reader.readAsBinaryString(file);
I've created a .net core class library that needs to embed external text files. I have added a Resource.resx to the project root and added my text files to the resx. I can now access the text files through code
var a = Resource.MyTxtResourceFile
The intellisense lets me know that MyTxtResourceFile "Looks up a localized string similar to [the correct contents of the file]
When I run the code Resource.MyTxtResourceFile actually returns the string
directory1\directory2\mytxtresourcefile.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8
not the contents of the text file.
The Resource.Designer looks something like this
/// <summary>
/// Looks up a localized string similar to [the contents of my text file]
/// </summary>
public static string MyTxtResourceFile {
get {
return ResourceManager.GetString("MyTxtResourceFile ", resourceCulture);
}
}
Can anyone help?
I no longer add things directly to the resx file. I just include text files in the project and use the GetManifestResourceStream method to get the contents, then use a StreamReader to turn the stream into a string.
For example, I have a project called Stamina.World.DataAccess.SqlClient. There is a file called ReadAll.sql in a subfolder AuthenticationAttempt\Script. I'd like to get the contents of that file. Here's the code
var manifestResourceName = "Stamina.World.DataAccess.SqlClient.AuthenticationAttempt.Script.ReadAll.sql";
var contents = string.Empty;
// this assumes the file is in the current assembly
var currentAssembly = this.GetType().Assembly;
using (var manifestResourceStream = currentAssembly.GetManifestResourceStream(manifestResourceName))
{
if (manifestResourceStream == null)
{
// TODO : handle this
}
using (var streamReader = new System.IO.StreamReader(manifestResourceStream))
{
contents = streamReader.ReadToEnd();
}
}
// do something with the file contents
I'm doing a file upload function in my ASP.NET MVC web system. The file upload function is working, so the next step I do is to validate the file size.
Please see the attached codes
Partial form GEDocumentInfoForm.ascx:
<input type="file" name = "Files" class = "multi" id = "myFile"/>
Main Form Create.aspx
<asp:Content ID="Content4" ContentPlaceHolderID="ContentCph" runat="server">
<script type="text/javascript">
$(document).on('click', '#btnCreateDocument', function () {
$('#btnCreateDocument').attr('disabled', 'disabled'); // prevent resubmit
Checksize()
document.body.style.cursor = 'wait';
});
function Checksize() {
alert(document.getElementById("myFile").tagName);
var k = document.getElementById("myFile").files[0].size;
alert("file size in KB " + k / 1024);
}
</script>
<% Using (Html.BeginForm("Create", "GEDocument", FormMethod.Post, New With {.enctype = "multipart/form-data", .id = "form"}))%>
<input type="submit" name="Save" value="<%= Detail.Save %>" id="btnCreateDocument" />
<div id="Div1">
<% Html.RenderPartial("GEDocumentInfoForm", Model) %>
</div>
<% End Using%>
</asp:Content>
The file size validation (not more than 2048B) was working fine in localhost. So, after that I published it and deploy in my development server. When I run it, somehow it can pass through my validation. After check in debug mode of web browser, it returns 0 for the file size.
var k = document.getElementById("myFile").files[0].size;
I've tried to search solutions to see if anyone hit the similar issue before. End up, I have to use server validation in my Controller.
Dim fileZs As HttpFileCollectionBase = Request.Files
For z As Integer = 0 To (fileZs.Count - 1)
Dim file As HttpPostedFileBase = fileZs(z)
If Not IsNothing(file) AndAlso (file.ContentLength / 1024) > 2048 Then
errors.Concat(New RuleViolation(Message.EmailMustHaveValue, "SelectedToEmails"))
End If
Next
Web.Config (added the configuration so that it can pass ActionFilterAttribute in Controller due to Maximum request too long)
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
I think that server validation is not user-friendly. I wish there are some answers from the experts if anyone faced the issue like me in doing Client validation to check file size in file upload feature.
Why is it always return 0 after published to development server?
Is it related to server security? As I know we are getting FileName as C:\fakePath\myFileName. Could it be some relationship over here?
here a full working example, note Request.Files is an array, if you are sending only one file you need to pick first item.
the right property to check is ContentLength
also check if in your folder the uploaded file exists after upload, because you need to have write permission in the folder where you are uploading
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
//............
}
There are some reference about File Uploading to Azure BY ASP.NET MVC but I can't find none in field of ASP.NET Webpages
How to implement such code to upload to Azure Storage?
Well.. For more information,
My goal is image uploading in CK Editor
but Due to Azure Hosting, ordinary CKEditor reference is not working.
So I googled and use this code block
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("lawimage");
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(name))
{
blockBlob.UploadFromStream(fileStream);
}
But it doesn't work,
and my 'web.config' is
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=lawcbt;AccountKey=[MyAccountKey]/>
</appSettings>
Is anyone ever did upload to Azure Storage via ASP.NET WebPages?
P.S> To be more clear, My 'upload.aspx' source file is this
upload.aspx
Sure, you have to upload the file first to you Asp.Net webpage. From there you can upload it to your blobstorage. In your code it seems you are trying to upload a file from the server to blobstorage. First you have to upload the file to server, and then you can send the stream to the blobstorage.
I have solved myself! By using Visual Studio, I found a bugging point. olleh!!
Even though I don't like Visual Studio, Visual Studio is very powerful tool Tongue Out
Maybe It's heavyness is worth for that.
This code will work!
<%# Import namespace="System.Configuration" %>
<%# Import namespace="Microsoft.WindowsAzure" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage.Auth" %>
<%# Import namespace="Microsoft.WindowsAzure.Storage.Blob" %>
......
HttpPostedFile theFile = HttpContext.Current.Request.Files[0];
// Azure Upload
// Retrieve storage account from connection string.
StorageCredentials sc = new StorageCredentials("[MyStorageName]", "[MyKey]");
CloudStorageAccount storageAccount = new CloudStorageAccount(sc, false);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("lawimage");
// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference(sFileName);
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = theFile.InputStream)
{
blockBlob.UploadFromStream(fileStream);
}
.....