How to get the Uploaded Files in MVC3? - asp.net-mvc-3

Hi all i am uploading the files uploaded by the user in this path
string savefilename = Path.Combine(Server.MapPath("~/Content/UploadedFiles/"),
Path.GetFileName());
And i am saving the Url in the Database in the Url Column in this
~/Content/UploadedFiles/BugTrackerDataBase.xlsx
and i am trying to retrieve the file Uploaded by the user by a link in my grid view
my retrieve method looks like this
public ActionResult ViewAttachments(string AttachmentName)
{
try
{
AttachmentName = Session["AttachmentUrl"].ToString();
var fs = System.IO.File.OpenRead(Server.MapPath("'" + AttachmentName + "'"));
return File(fs, "application/doc", AttachmentName);
}
catch
{
throw new HttpException(404, "Couldn't find " + AttachmentName);
}
}
and i have the Excepiton
"Could not find a part of the path 'D:\AnilWork\BugTracker\BugTracker\ViewBug\'UploadedFiles\BugTrackerDataBase.xlsx''."
can any one tell me where am i doing wrong or the write procedure to do this

That is because you have " ' " in your path.
\BugTracker\ViewBug\'UploadedFiles\BugTrackerDataBase.xlsx''
Remove them an it should work. Like this
var fs = System.IO.File.OpenRead(Server.MapPath(AttachmentName));

try
var fs = System.IO.File.OpenRead(Server.MapPath(" + AttachmentName + "));
instead of
var fs = System.IO.File.OpenRead(Server.MapPath("'" + AttachmentName + "'"));
it shoud be replaced with (Server.MapPath(""+ AttachmentName + ""))

Related

xxxxxx is not a valid path. Make sure that the path name is

I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}

Unable to upload files greater than 7KB via ajax call to servlet over https

I am running JBoss 6.3 portal and have deployed a war file containing following two files
1) DocUpload.jsp
Containing following code snippet making an ajax call to send the mentioned fields in data2 along with file object fd.
fd.append('file', document.getElementById('file1').files[0]);
data2 = encodeURIComponent(document.getElementById("lob").value)+'#'+encodeURIComponent(document.getElementById("loantype").value)+
'#'+encodeURIComponent(document.getElementById('docType').value)+'#'+encodeURIComponent(document.getElementById('docName').value)+
'#'+encodeURIComponent(document.getElementById('entity').value)+'#'+encodeURIComponent(document.getElementById('userName').value)+
'#'+encodeURIComponent(document.getElementById('PartyName').value)+'#'+encodeURIComponent(document.getElementById('loanAccount').value)+
'#'+encodeURIComponent(document.getElementById('LoanAmount').value)+'#'+encodeURIComponent(e4)+'#'+encodeURIComponent(document.getElementById('hiddenWIName').value)+'#'+encodeURIComponent(e3);
alert("data2 "+data2);
var ret = doPostAjax("${pageContext.request.contextPath}/AddDocumentsServlet?data="+data2,fd);
2) AddDocumentsServlet.java
Containing code for handling the request
File path = new File(RootFolderPath + File.separator + "Portal_TmpDoc" + File.separator + todayAsString + File.separator + lMilliSecondsCurrent);
UploadPath = path.getAbsolutePath();
if (!path.isDirectory()) {
path.mkdirs();
}
if (isMultipart) {
System.out.println("Inside if isMultipart");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
//List multiparts = upload.parseRequest(request);
System.out.println("Before parsing request");
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("multiparts :::"+multiparts);
for (Iterator iterator = multiparts.iterator(); iterator.hasNext();) {
FileItem item = (FileItem) iterator.next();
logger.info(item);
if (!item.isFormField()) {
String fileobject = item.getFieldName();
System.out.println(request.getParameter("data"));
String[] fileArray = request.getParameter("data").split("#");
name = new File(item.getName()).getName();
name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
ext = name.substring(name.lastIndexOf(".") + 1);
logger.info(name);
File directory = new File(UploadPath);
File[] afile;
int j = (afile = directory.listFiles()).length;
for (int i = 0; i < j; i++) {
File f = afile[i];
if (f.getName().startsWith(filename))
f.delete();
}
item.write(new File(UploadPath + File.separator + filename + "." + ext));
System.out.println("File Uploaded");
}
}
My problem is when I use http connection for the above requests and getting session the program runs just fine. But while using https and uploading file greater than 7 KB the page becomes unresponsive.
On further analysis I found that the program flow gets stuck on this line
List<FileItem> multiparts = upload.parseRequest(request);
and despite having this line in a try block no exception is caught.

MVC Rotativa.ActionAsPdf generate Unauthorized in pdf

Rotativa.ActionAsPdf is working fine when you have set Anonymous access true in IIS. but when you select window authentication , the Rotativa.ActionAsPdf Generate pdf with error Unauthorized etc.
google a lot could not find any solution ..
here is my solution :::
create a standard user name in your AD (Active directory) and use this user name and password to generate the file.
example
string iFilename = "eForms_" + Id + "_" + DateTime.Now.ToString("dd_mm_yyyy_hh_mm_ss") + ".pdf";
ViewBag.FileName = Server.MapPath("~" + "/Files/" + iFilename);
var iResult = new Rotativa.ActionAsPdf("displayForm", new { Id = Id }) { FileName = iFilename, SaveOnServerPath = Server.MapPath("~" + "/Files/" + iFilename) };
iResult.UserName = "genericuser";
iResult.Password = "password";
return iResult;

CKEditor file upload doesn't work properly with mvc 6

I'm trying to use the built in upload file of CKEditor, it works with my MVC5 project, but it doesn't work with my MVC6 project, the code for uploading the file is correct, I've tested it, and it actually upload the file to the server, but it doesn't populate the form with the URL and image information, here's the code for my MVC5 project that works:
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.ContentLength > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + Path.GetFileName(upload.FileName);
var vFolderPath = Server.MapPath("/Upload/");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
upload.SaveAs(vFilePath);
vImagePath = Url.Content("/Upload/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch(Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And here is the code for MVC6 project that doesn't work:
public async Task<ActionResult> UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.Length > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
var vFolderPath = Path.Combine(_environment.WebRootPath, "Files", "ArticleUploads");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
await upload.SaveAsAsync(vFilePath);
vImagePath = Url.Content("/Files/ArticleUploads/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch (Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And in CKEditor config file I have:
config.filebrowserImageUploadUrl = '/Admin/Article/UploadImage';
I've inspected the variables, and they send the same value, also worth to note that I'm using the same version of CKEditor, so that can't be the problem, I'd appreciate any help on this.
If the file gets uploaded and you don't see the image gets populated, I guess there should be some problem with the way you return your content, since you are returning html, try to specify your content type, like so:
return Content(vOutput, "text/html");
If that didn't solve your problem, you need to provide more information, tell us what exactly you get from this action in JavaScript side.

Ace editor - It doesn´t change the error window dynamically

I have the next code:
var exeWindow = document.getElementById("exeWindow");
var errorWindow = document.getElementById("errorWindow");
var annot = editor.getSession().getAnnotations();
editor.getSession().on("changeAnnotation", execute);
function execute(){
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key))
console.log(annot[key].text + "on line " + " " + (parseInt(annot[key].row)+1));
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Im trying to capture the error logs, and before execute a valid code works, but once I introduce for example 2+2, despite of exeWindow changes correctly, if a rewrite it to 2+a for example, searching a new error, the exeWindow doesn´t changes and the error does not appears in errorWindow.
EDIT: Sorry, the problem is that is not getting the correct errors, only the errors like 'missing semicolon'.
If someone is interested, the solution I found is the next one:
function execute(){
try {
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
} catch(err){
var annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key)){
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
}
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Simple as that :)

Resources