unable to upload file on server "Error 500 Inter server Error" - asp.net-mvc-4

I am stuck in upload file it works fine on local but when I deploy on server it show
500 internal server Error..
Here its my code please review..where m wrong?
Here's my controller code
[HttpPost]
public ActionResult GlovalValues(Global_values REC, HttpPostedFileBase uploadFile)
{
string strPath = "~/Laptop_File/";
string Server_path = "";
string GetFileName = "";
int id = REC.ID;
string Desc = REC.GS_Desc;
string Name = REC.GS_Name;
string values = REC.GS_Values;
int Effrows = 0;
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
if (!Directory.Exists(Server.MapPath(strPath)))
{
DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(strPath));
}
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
var filePath = Request.FilePath;
var FileExtension = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.') + 1).ToLower();
string ActualFileName = uploadFile.FileName;
GetFileName = Path.GetFileNameWithoutExtension(uploadFile.FileName);
if (file != null && file.ContentLength > 0)
{
string UploadFileName = Path.GetFileName(GetFileName + "." + FileExtension);
Server_path = Path.Combine(Server.MapPath("~/Laptop_File/"), UploadFileName);
if (FileExtension == "xlsx" || FileExtension == "xltx" || FileExtension == "xls" || FileExtension == "xlt ")
{
file.SaveAs(Server_path);
}
}
}
}
catch (Exception ex)
{
throw;
}
}
return RedirectToAction("Global_Values_List", "GS_Global_Values");
}
here's my view
#using (Html.BeginForm("GlovalValues", "GS_Global_Values", FormMethod.Post, new { #id = "id", #enctype = "multipart/form-data" }))
{
<div class="form-group">
<label> Uplaod File : </label>
<div class="col-md-10">
<input type="file" name="uploadFile" id="fileupload" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
Please help I cant figure out whats wrong

In my case it reason from permission.When I ran my project locally on IIS Express everything was fine,and I could upload files correctly, but when I deployed it on IIS 8,it had returned me "Error 500 Internal server Error" for file uploading.
I have changed the permissions for "IIS_IUSRS" on "upload" folder in IIS 8 as follows:
now it is working fine.

Check on server that your application pool has rights of network services or other user with higher authority to Modify the directory & file writing.
If your code is working in local this seems the only issue at moments.

Related

How to fix NullPointerException when uploading picture in database?

I want to upload a picture in database, and this is my jsp:
<body>
<form action="addbooka" method="POST" enctype="multipart/form-data">
Title:<input type="text" value="${title}" name="title"> <br>
Description: <input type="text" value="${description}" name="description"><br>
Price: <input type="text" value="${price}" name="price"><br>
Picture: <input type="file" name="myimg"><br>
<button type="submit">Add</button>
</form>
</body>
And this is method where i insert picture:
public static void insertImage(String myImage) throws Exception {
try {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
File file = new File(myImage);
InputStream in = new FileInputStream(file);
ps.setBlob(1, in);
ps.executeUpdate();
In servlet i just call this method and pass request.getParameter("myimg") as an argument(input tag).
After some research i think i get this error because i did't put boundary in form tag. But i can't wrap my head around what numbers to put, what to do next or is it really error because of boundary or something else?
In your servlet don't forget to put #MultipartConfig annotation.Also , you are passing string to your method instead that should be Part . i.e :
int row=0;
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("myimg");//get image
insertImage(filePart)//pass to method
public static void insertImage(Part filePart) throws Exception {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
ps.setBlob(1, inputStream);
}
row = ps.executeUpdate();
if (row > 0) {
out.println("done")
}
}

Cannot get Blazor file upload to upload file

I have a Blazor app where Im using BlazorInputFile from this website - https://blog.stevensanderson.com/2019/09/13/blazor-inputfile/ however the page only loads it to a Memory Stream, not copy the file to a folder on the server. I need it to copy to a folder on the server.
<div class="form-group">
<label for="taskName">Feature Image</label>
<InputFile OnChange="HandleFileSelected" />
</div>
#code {
IFileListEntry file;
void HandleFileSelected(IFileListEntry[] files)
{
file = files.FirstOrDefault();
}
async Task CountLines()
{
numLines = 0;
using (var reader = new System.IO.StreamReader(file.Data))
{
while (await reader.ReadLineAsync() != null)
{
numLines++;
}
}
}
async Task UploadFile()
{
if (file != null)
{
var path = System.IO.Path.Combine(Server.MapPath("~/Uploads/"));
string pathstring = System.IO.Path.Combine(path.ToString());
string filename1 = Guid.NewGuid() + System.IO.Path.GetExtension(file.Name);
bool isexists = System.IO.Directory.Exists(path);
if (!isexists)
{
System.IO.Directory.CreateDirectory(pathstring);
}
string uploadpath = pathstring + "\\" + filename1;
file.SaveAs(uploadpath);
}
}
In the code above I have created a UploadFile method and taken my usual way of uploading files, but obviously it wont work because IFileListEntry does not have the SaveAs method and Server will not work on Blazor.
How am I best uploading this file to the server please? (UploadFile method will get called on form submit).

Sharepoint 2013 - FBA and 2FA with custom login page

I'm a complete noob in Sharepoint. I've just started learning sharepoint 2 weeks ago coz my boss assigned me to a sharepoint project. I have to implement 2FA and FBA in an existing claims based intranet web application. I though it would be a simple task to do just by researching but I haven't found a clear guide or answer for my question.
Here are a few of my tasks:
1) Add forms based authentication to the site and use custom login page.
2) Authentication
Check user's name and password with AD upon login.
If valid, have to request OTP code from the 3rd party provider for
2FA.
User is authenticated after passing both.
Configurations and custom login page were not much trouble and it didn't take long to get them done. But I'm stuck at the 2FA part.
1) How to customize the authentication process? I don't remember where did I get the below code but I really hoped that I would be able to do something with it. So, can I do something with it or I'm going the wrong path? I'd really appreciate any help and thanks a lot in advance.
protected void btnLogin_Click(object sender, EventArgs e)
{
bool status = SPClaimsUtility.AuthenticateFormsUser(
Context.Request.UrlReferrer,
txtUsername.Value.ToString(),
txtPassword.Value.ToString());
if (!status) // if auth failed
{
lblInvalid.InnerText = "Wrong Username or Password";
lblInvalid.Visible = true;
}
else //if success
{
//What do I do here to change the user back to not authenticated?
}
}
After you properly log in set federated authentication cookie domain.
HttpCookie httpCookie = current.Response.Cookies["FedAuth"];
httpCookie.Domain = "." + ConfigurationManager.AppSettings["yourdomain"];
Sign out method is more complicated, long time ago i based my solution on this post
And sign out method (sorry for variable names but i'm decompiling my old dll) based on sharepoint SignOut page and fix from the post:
public static void SignOut(SPSite site, SPWeb web, IClaimsPrincipal principal)
{
HttpContext current = HttpContext.Current;
if (current.Session != null)
{
current.Session.Clear();
}
string value = string.Empty;
if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
{
value = "NoCookie";
}
HttpCookie httpCookie = current.Request.Cookies["WSS_KeepSessionAuthenticated"];
bool flag = false;
for (int i = 0; i < current.Request.Cookies.Count; i++)
{
HttpCookie httpCookie2 = current.Request.Cookies.Get(i);
if (httpCookie2.Name == "FedAuth" && !flag)
{
flag = true;
httpCookie2.Domain = WebConfigurationManager.AppSettings["yourdomain"];
}
}
if (httpCookie != null)
{
httpCookie.Value = value;
current.Response.Cookies.Remove("WSS_KeepSessionAuthenticated");
current.Response.Cookies.Add(httpCookie);
}
HttpCookie httpCookie3 = current.Request.Cookies["MSOWebPartPage_AnonymousAccessCookie"];
if (httpCookie3 != null)
{
httpCookie3.Value = value;
httpCookie3.Expires = new DateTime(1970, 1, 1);
current.Response.Cookies.Remove("MSOWebPartPage_AnonymousAccessCookie");
current.Response.Cookies.Add(httpCookie3);
}
SPIisSettings iisSettingsWithFallback = site.WebApplication.GetIisSettingsWithFallback(site.Zone);
if (iisSettingsWithFallback.UseClaimsAuthentication)
{
string iPUrl = Authentication.GetIPUrl(principal);
if (iPUrl != string.Empty)
{
string str = HttpUtility.UrlEncode(SPContext.Current.Site.RootWeb.Url);
string url = iPUrl + "?wa=wsignout1.0&wreply=" + str;
FederatedAuthentication.SessionAuthenticationModule.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
current.Response.Redirect(url);
}
else
{
FederatedAuthentication.SessionAuthenticationModule.SignOut();
int num = 0;
foreach (SPAuthenticationProvider current2 in iisSettingsWithFallback.ClaimsAuthenticationProviders)
{
num++;
}
if (num != 1 || !iisSettingsWithFallback.UseWindowsIntegratedAuthentication)
{
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
return;
}
}
}
if (AuthenticationMode.Forms == SPSecurity.AuthenticationMode)
{
FormsAuthentication.SignOut();
if (current.Session != null)
{
current.Session.Abandon();
}
SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
}
else if (AuthenticationMode.Windows != SPSecurity.AuthenticationMode)
{
throw new SPException();
}
}
private static string GetIPUrl(IClaimsPrincipal principal)
{
string result;
if (principal == null)
{
result = string.Empty;
}
else
{
string text = string.Empty;
try
{
string text2 = principal.Identity.Name.Split(new char[] {'|'})[1];
if (SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2] != null)
{
text = SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2].ProviderUri.AbsoluteUri;
}
}
catch (Exception ex)
{
// log
}
result = text;
}
return result;
}
Further reading:
Writing A Custom Forms Login Page for SharePoint 2010
Custom Single Sign-On Scenario in SharePoint 2010
Normal aspx page
<html>
<head>One Head</head>
<body>
<form runat="server">
<table>
<tr>
<td>User Name:</td>
<td>
<asp:TextBox ID="txtUserName" runat="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" TextMode="Password" runat="server" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnButton" Text="Button" OnClick="btnButton_Click" runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>
You may have trouble in adding Microsoft.SharePoint.identityModel, here is the location I got
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll
List of Includes
using System;
using Microsoft.SharePoint;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel.Tokens;
Button click code
protected void btnButton_Click(object sender, EventArgs e)
{
string domn = "mydomain";
string membershipProviderName = "membership";
string roleProviderName = "rolemanager";
string cookieeee = string.Format("{0}\\{1}", domn, txtUserName.Text);
bool isAuthenticated = Authenticate(domn, txtUserName.Text, txtPassword.Text);
if (isAuthenticated)
{
SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url),
membershipProviderName, roleProviderName, txtUserName.Text, txtPassword.Text,
SPFormsAuthenticationOption.PersistentSignInRequest);
SPFederationAuthenticationModule.Current.SetPrincipalAndWriteSessionToken(token);
Response.Redirect("/");
}
}
[DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted = true)]
public static bool Authenticate(string domainName, string userAlias, string userPassword)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName);
return context.ValidateCredentials(userAlias, userPassword, ContextOptions.Negotiate));
}
catch
{
throw;
}
}
Note: Make sure you have all FBA configurations set in web config files. This is only custom authentication this will not work if role and membership are not set properly in the central admin and web config on services and webapplication.

how to pass posted file using ajax beginform in mvc?

I have following in my partial view.
#using (Ajax.BeginForm("xyz", "xyz", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileName" id="FileName" style="width:240px" />
<input type="submit" value="Upload" onclick="submit()" />
}
in my controller following is method.
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult xyz(HttpPostedFileBase FileName)
{
var httpPostedFileBase = Request.Files["FileName"];
if (httpPostedFileBase != null && httpPostedFileBase.ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(httpPostedFileBase.FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/SavedFiles"), extension);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
httpPostedFileBase.SaveAs(path1);
}
ViewData["Status"] = "Success";
return Json("test", JsonRequestBehavior.AllowGet);
}
From the above i should get the file on my controller that is posted but it does not give me file instead gives null on controller action.
Please suggest.

When uploading files to ASP.Net 5 Web API, the collection of IFormFile is empty

I am trying to upload some files from a console application to an ASP.NET 5 WEB API service.
Client (console app):
private static HttpResponseMessage UploadFiles(string[] files, Uri uploadEndpoint)
{
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var fs = new FileStream(file, FileMode.Open);
var index = file.LastIndexOf(#"\");
var fn = file.Substring(index + 1);
fs.Position = 0;
content.Add(new StreamContent(fs), "file", fn);
}
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = uploadEndpoint;
var client = new HttpClient();
return client.SendAsync(message).Result;
}
Server (Asp.Net 5) Web API
[HttpPost("upload")]
public IActionResult UploadFiles(ICollection<IFormFile> files)
{
var streams = files.Select(f => f.OpenReadStream()).ToArray();
var names = files.Select(f => ContentDispositionHeaderValue.Parse(f.ContentDisposition).FileName).ToArray();
ProcessFiles(streams, names);
return new HttpOkResult();
}
Unfortunately the collection of IFormFile is always empty.
Anyone can tell me why?
Thanks
Manu
Your upload controller expects the name identifier of the posted data to be files, not file.
This line: content.Add(new StreamContent(fs), "file", fn);
should be: content.Add(new StreamContent(fs), "files", fn);
So your code basically works, it was just a simple mistake.
You need to set the enctype of the form to multipart/form-data. Something like this.
<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
<input type="file" name="files" multiple/>
<input type="submit" value="Upload" />
</form>
I ran into this identical issue and it turned out that I was just missing - name="files" from <input type="file" name="files" multiple /> from HTML.