Issue faced reading an entry name from Tar InputStream - 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.

Related

Web API Upload File to Different Directory

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 "";
}

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

Downloading Multiple files from FTP Server using JSCH

I want to download all the files from FTP server using JSCH.
Below is the code snippet,
List<File> fileList = null;
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFolder);
for (ChannelSftp.LsEntry file : list) {
if( getLog().isDebugEnabled() ){
getLog().debug("Retrieved Files from the folder is"+file);
}
if (!(new File(file.getFilename())).isFile()) {
continue;
}
fileList.add(new File(remoteFolder,file.getFilename())) ;
return fileList;
The method will return List, for another method to download the files from the remote server using sftpChannel.get(src,dest) ;
Please let me know if the code is ok.
I don't have an environment to test, so can't confirm it.
But somewhat similar code i wrote for FTPClient and it works.
Appreciate your help.
You can use SftpATTRS to get the file information. You can declare a wrapper class to store file information. An example shown below.
private class SFTPFile
{
private SftpATTRS sftpAttributes;
public SFTPFile(LsEntry lsEntry)
{
this.sftpAttributes = lsEntry.getAttrs();
}
public boolean isFile()
{
return (!sftpAttributes.isDir() && !sftpAttributes.isLink());
}
}
Now you can use this class to test if the LsEntry is a file
private List<SFTPFile> getFiles(String path)
{
List<SFTPFile> files = null;
try
{
List<?> lsEntries = sftpChannel.ls(path);
if (lsEntries != null)
{
files = new ArrayList<SFTPFile>();
for (int i = 0; i < lsEntries.size(); i++)
{
Object next = lsEntries.get(i);
if (!(next instanceof LsEntry))
{
// throw exception
}
SFTPFile sftpFile = new SFTPFile((LsEntry) next);
if (sftpFile.isFile())
{
files.add(sftpFile);
}
}
}
}
catch (SftpException sftpException)
{
//
}
return files;
}
Now you can use sftpChannel.get(src,dest) ; to download files.

List all files, dirs and subdirs with tomahawk tree

I've been using tomahawk (1.1.11) for a project. I want to display a tree with all the files and subdirs (and files in those subdirs). I have a code, but it's not listing all of the files and dirs, and don't know where's the mistake.
public TreeNode getTreeData() {
path = loadConfiguredPath();
String dependencia = userVerifier.getDependencia();
if (dependencia.equals("TEST")) {
path = path + "dataFiles";
} else {
path = path + "dataFiles\\" + dependencia;
}
dirRoot = new File(path);
treeRoot = new TreeNodeBase("folder", "BASEDIR", false);
createTree(dirRoot, treeRoot);
return treeRoot;
}
private void createTree(File fileRoot, TreeNode treeRoot) {
File[] files = fileRoot.listFiles();
TreeNodeBase tnb;
for (File f : files) {
if (f.isDirectory()) {
tnb = new TreeNodeBase("folder", f.getName(), false);
treeRoot.getChildren().add(tnb);
createTree(f, tnb);
}
if (f.isFile()) {
tnb = new TreeNodeBase("file", f.getName(), false);
treeRoot.getChildren().add(tnb);
//return;
}
}
return;
}
UPDATE: code corrected as mention in comment.
Sorry, finally found my error !
I was returning when just one file was found. and I just change that return at the end of the for loop.
Thanks anyway

Failed to upload image saved on server

I am saving an image file at server. The file is successfully saved at the server but when I try to assign the URL of that file to the image control, the image is failed to load but when I assign that url directly in to HTML code, the file is loaded successfully. Please guide me Where I am making a mistake. Below are the code for my file upload and fetch URL.
Code For File Upload
private string ImageUpload()
{
try
{
string FileName = UpldCompanyLogo.FileName;
if (UpldCompanyLogo.HasFile)
{
string SaveFilePath = Server.MapPath("~\\Upload\\")+FileName;
if (!Directory.Exists(Server.MapPath("~\\Upload\\")))
Directory.CreateDirectory(Server.MapPath("~\\Upload\\"));
if (File.Exists(SaveFilePath))
{
File.Delete(SaveFilePath);
}
if(File.Exists(ViewState["ImageURL"].ToString()))
{
File.Delete(ViewState["ImageURL"].ToString());
}
UpldCompanyLogo.PostedFile.SaveAs(SaveFilePath);
}
return FileName;
}
catch (Exception ex)
{
if (ex.HelpLink == null)
ex.HelpLink = "Controls_Company103>>" + ex.Message;
else
ex.HelpLink = "Controls_Company103>>" + ex.HelpLink;
lblMessage.Text = ex.HelpLink;
lblMessage.CssClass = "ERROR";
return null;
}
}
This is the code to get the image URL
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
string path = Server.MapPath("~\\Upload\\");
imgLogo.ImageUrl = path + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}
If I copy and past the retrieved path in the browser, the image is found there at the server.
You may try this:
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
imgLogo.ImageUrl = Page.ResolveUrl("~\\Upload\\") + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}

Resources