Web API Upload File to Different Directory - asp.net

is it possible to upload files using Web API to a different directory and not just on the App Root Folder? Either folder on the same server outside App Root Folder or another server.
I need to upload files using Web API to another directory with more space.
public HttpResponseMessage Post()
{
try
{
string mydir = "~/Files/"; //-- APP ROOT FOLDER --//
if (!(Directory.Exists(HttpContext.Current.Server.MapPath(mydir))))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(mydir));
}
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string filename = string.Concat(GetActualFilename(postedFile.FileName), GetExtension(postedFile.FileName));
var filePath = HttpContext.Current.Server.MapPath(mydir + "/" + filename);
postedFile.SaveAs(filePath);
}
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, "No file attached/processed.");
}
return Request.CreateResponse(HttpStatusCode.Created, "Successfully uploaded file(s).");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
private static string GetActualFilename(string filename)
{
for (int i = filename.Length - 1; i >= 0; i--)
{
if (filename[i] == '.')
{
return filename.Substring(0, i);
}
}
return filename;
}
private static string GetExtension(string filename)
{
for (int i = filename.Length - 1; i >= 0; i--)
{
if (filename[i] == '.')
{
return filename.Substring(i);
}
}
return "";
}

Related

Xamarin Forms Delete Web Cache / Javascript Storage

I have an app that is using an http server to serve files to a Web View. The web viewers are caching image links which is causing broken images when their paths changes.
I can delete the web store on Android and UWP but I cannot figure out how to properly with iOS.
Android:
Android.Webkit.WebStorage.Instance.DeleteAllData();
UWP:
Windows.UI.Xaml.Controls.WebView.ClearTemporaryWebDataAsync();
I have tried the following with no luck:
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(
websiteDataTypes: record.DataTypes,
date: new[] { record },
completionHandler: ()=> { });
}
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
NSUrlCache.SharedCache.DiskCapacity = 0;
NSUrlCache.SharedCache.MemoryCapacity = 0;
Found the answer at: https://gochannel.org/links/link/snapshot/640
Rewrote to Xamarin IOS
private void DeleteCachedFiles()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
}
else
{
// Remove the basic cache.
NSUrlCache.SharedCache.RemoveAllCachedResponses();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies;
foreach (var c in cookies)
{
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
}
try
{
// Clear web cache
DeleteLibraryFolderContents("Caches");
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
DeleteLibraryFolderContents("Cookies");
// Removes all app cache storage.
DeleteLibraryFolder("WebKit");
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting cache {ex.Message}");
}
}
private void DeleteLibraryFolder(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
manager.Remove(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
private void DeleteLibraryFolderContents(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
var contents = manager.GetDirectoryContent(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
foreach (var c in contents)
{
try
{
manager.Remove(Path.Combine(dir, c), out NSError errorRemove);
if (errorRemove != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting folder contents: {folderName}{Environment.NewLine}{ex.Message}");
}
}
}

Issue faced reading an entry name from Tar InputStream

Facing problem regarding reading archive file recursively. I have created one recursive program which reads entry name from tar file or zip etc and will exit when some xyz extension found.
The code executes absolutely fine with proper entry name including archives having extension(eg, .zip,.tar,.tar.gz,.tgz), but it throws junk characters if the entry name is archive, but archive has no extension.
Eg: One archive inside another archive with no extension, viz, Ming_2nd.tar contains archive Ming_2nd which is an archive format
The following are the code and output.
public static String readTar4SrcType(TarInputStream tarInpStream) throws Exception{
TarEntry tarEntry = null;
int cnt = 0;
try {
tarEntry = tarInpStream.getNextEntry();
} catch (IOException e) {
src = "Other";
}
while (tarEntry != null) {
cnt++;
if (tarEntry.isDirectory()) {
System.out.println("Inside directory 4 Tar File..");
} else {
if (src.equals("tex") || src.equals("doc") || src.equals("docx")) {
break;
} else {
String entryName = tarEntry.getName();
System.out.println("entryName : " + entryName);
if(entryName.lastIndexOf("/")!=-1){
if (entryName.endsWith(".tar") || entryName.endsWith(".tar.gz") || entryName.endsWith(".tgz")){
readTar4SrcType(tarInpStream);
tarInpStream = null;
} else if (entryName.endsWith(".zip")) {
ZipInputStream zins = new ZipInputStream(tarInpStream);
readZIP4SrcType(zins);
zins = null;
} else if (entryName.endsWith(".tex")) {
System.out.println("TEX found...break");
src = "tex";
break;
} else if (entryName.endsWith(".doc") || entryName.endsWith(".docx")) {
System.out.println("DOC found...break");
src = "doc";
break;
} else {
src = "Other";
}
} else{
if(entryName.endsWith(".tex")){
src = "tex";
System.out.println("TEX found...break");
break;
} else if(entryName.endsWith(".doc") || entryName.endsWith(".docx")){
System.out.println("DOC found...break");
src = "doc";
break;
} else {
System.out.println("Invalid file format");
src = "Other";
}
}
}
}
tarEntry = tarInpStream.getNextEntry();
}
if(cnt==0) {
src = "Other";
}
return src;
}
??#????+^??NW}??C????????Y?c?>?uM??1??v?Q7????;Z8?DQ=?o??
Invalid file format
entryName : ?zv????????????3?^:??????|?>t?%oN???.5;??%z????_??kiqFt??l\?X??,m?????b
'?x(???????J5??j?x?%??
Invalid file format
entryName : +Dw???m?-?)????Ck??????4???>? ?e/???????^#????2?x$???z????????
entryName : ?~??Z
#5\?????&J7??{c?w{
Please provide me the solution as I am stuck for many days.

Cannot find part of path while uploading image to a folder in Asp.net

I am uploading a profile picture of a user to a folder and saving its path to RavenDB. But my code is giving me an error that part of path is not found. On this line
file.SaveAs(path);
Code:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType);
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
You have a typing error in your path...
Replace...
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
With...
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), FileName);
You also need to make sure you have the relevant permissions to write to this directory.
Based on your error, the filepath looks incorrect.
c:\users\wasfa\documents\visual studio
2012\Projects\MvcMembership\MvcMembership\App_Data\Uploads\daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg
is daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg the name of the file?
Try:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
Before file.SaveAs(path), try to check directory exist, if not, create one,
if(CreateFolderIfNeeded(path);
{
file.SaveAs(path);
}
A private function to create directory if needed,
private static bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{ result = false; }
}
return result;
Hope this helps.
Check the var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType); line in your code.
The file.ContentType will not return the extension of the file you are uploading. It shuold be like daed3def-df2b-4406-aa‌​9e-c1995190aa6d.jpeg instead of daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg
find the extension from the uploaded file using substring.
Hope this help

Url rewriting worked with virtual directory but not worked with root directory

I have a domain named like mydomain.com. I have used Url rewritting from https://www.simple-talk.com/dotnet/asp.net/a-complete-url-rewriting-solution-for-asp.net-2.0/ link. When I applied it on my virtual directory cretaed in mydomain.com it worked properly , but when i aaplied it on my domain directly i.e. from root it does not worked.
void RewriteModule_BeginRequest(object sender, EventArgs e)
{
RewriteModuleSectionHandler cfg = (RewriteModuleSectionHandler)ConfigurationManager.GetSection("modulesSection/rewriteModule");
// module is turned off in web.config
if (!cfg.RewriteOn) return;
string path = HttpContext.Current.Request.Path;
// there us nothing to process
if (path.Length == 0) return;
// load rewriting rules from web.config
// and loop through rules collection until first match
XmlNode rules = cfg.XmlSection.SelectSingleNode("rewriteRules");
foreach (XmlNode xml in rules.SelectNodes("rule"))
{
try
{
Regex re = new Regex(cfg.RewriteBase + xml.Attributes["source"].InnerText, RegexOptions.IgnoreCase);
Match match = re.Match(path);
if (match.Success)
{
path = re.Replace(path, xml.Attributes["destination"].InnerText);
if (path.Length != 0)
{
// check for QueryString parameters
if (HttpContext.Current.Request.QueryString.Count != 0)
{
// if there are Query String papameters
// then append them to current path
string sign = (path.IndexOf('?') == -1) ? "?" : "&";
path = path + sign + HttpContext.Current.Request.QueryString.ToString();
}
// new path to rewrite to
string rew = cfg.RewriteBase + path;
// save original path to HttpContext for further use
HttpContext.Current.Items.Add(
"OriginalUrl",
HttpContext.Current.Request.RawUrl);
// rewrite
HttpContext.Current.RewritePath(rew);
}
return;
}
else
{
// HttpContext.Current.RewritePath("~/FnF.aspx");
}
}
catch (Exception ex)
{
throw (new Exception("Incorrect rule.", ex));
}
}
return;
}
public class RewriteModuleSectionHandler : IConfigurationSectionHandler
{
private XmlNode _XmlSection;
private string _RewriteBase;
private bool _RewriteOn;
public XmlNode XmlSection
{
get { return _XmlSection; }
}
public string RewriteBase
{
get { return _RewriteBase; }
}
public bool RewriteOn
{
get { return _RewriteOn; }
}
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
// set base path for rewriting module to
// application root
_RewriteBase = HttpContext.Current.Request.ApplicationPath;
if (!HttpContext.Current.Request.ApplicationPath.EndsWith("/"))
{
_RewriteBase = HttpContext.Current.Request.ApplicationPath + "/";
}
// process configuration section
// from web.config
try
{
_XmlSection = section;
_RewriteOn = Convert.ToBoolean(section.SelectSingleNode("rewriteOn").InnerText);
}
catch (Exception ex)
{
throw (new Exception("Error while processing RewriteModule configuration section.", ex));
}
return this;
}
}
Use Regex re = new Regex("^" + cfg.RewriteBase + xml.Attributes["source"].InnerText+"$", RegexOptions.IgnoreCase);
instead of Regex re = new Regex(cfg.RewriteBase + xml.Attributes["source"].InnerText, RegexOptions.IgnoreCase); Now it worked for me.

How to create zip file in asp.net

I need to create zip file from the folder, path:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild\HOST
within that host folder there are 7 txt files.
I want to create zip file HOST.zip in the folder above:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild
I've used Ionic ZIP for this in our own projects.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
public class Ziper
{
public static string MapPathReverse(string fullServerPath)
{
return #"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty);
}
public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
{
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
System.Web.HttpContext c = System.Web.HttpContext.Current;
//String ReadmeText = String.Format("README.TXT\n\nHello!\n\n" +
// "This is text for a readme.");
string archiveName = String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
var path = Server.MapPath(#"../Images/TempFile/TempFile" + DateTime.Now.Ticks);
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
var pathzipfile = Server.MapPath(#"../Images/TempFile/zip_" + DateTime.Now.Ticks + ".zip");
for (int i = 0; i < pathes.Length; i++)
{
if (File.Exists(pathes[i]))
{
string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
File.Copy(pathes[i], dst);
}
}
if (File.Exists(pathzipfile))
File.Delete(pathzipfile);
ZipFile.CreateFromDirectory(path, pathzipfile);
{
byte[] bytes = File.ReadAllBytes(pathzipfile);
Response.OutputStream.Write(bytes, 0, bytes.Length);
}
Response.Close();
File.Delete(pathzipfile);
Directory.Delete(path, true);
}
public Ziper()
{
}
}

Resources