I am having a bit of trouble trying to delete a file from the applications private storage directory that I have programmatically created and compressed.
The problem I am facing is that it's not recognising that the file exists when I call file.exists(), and so it will not delete the file.
This is the code I'm using to delete the file
public static void deleteImageFromPrivateArea( final String fileUri )
{
final File file;
boolean isFileDeleted;
if ( isFilePathPrefixPresent( fileUri ) )
{//file name checking
file = new File( fileUri );
}
else
{
file = new File( "file://" + fileUri );
}
if ( file.exists() )
{
isFileDeleted = file.delete();
if ( ! isFileDeleted )
{
throw new IllegalStateException( "File was not deleted" );
}
}
}
To clear things up, I know that the fileUri I'm passing through is the location of a file that currently exists. I have checked with a filemanager app.
I have the permissions set up in the manifests xml.
What I believe is happening is that this code is getting the path of the currently existing file, and setting up a new file but not writing the data to it thus this new file does not exist in android.
So what I think I need to do is get the existing file (maybe not in the form of a Uri, but the actual file) and then call .delete() as then the file would exist.
Or
After setting up this new file with the fileUri, write the data to it using an OutputfileStream - this would not be my preferred method though.
-but I'm not entirely sure.
would be easier just to pass the filename as a parameter then do
File mydir = getFilesDir(); //get your internal directory
File myFile = new File(mydir, filename);
myFile.delete();
With help from BradR I found the best solution.
I used *getExternalFilesDir( Environment.DIRECTORY_PICTURES )* to get the pictures 2. directory in the applications private storage area.
Created a new file with the given imageUri and then used this to get the filename of the file.
Reinitialized the File to create a new file using the ExternalFilesDir and filename
Check that the file exists and delete it.
#
public static void deleteImageFromPrivateArea( final Context context, final String imageUri )
{
String filename;
File file;
final File dir = context.getExternalFilesDir( Environment.DIRECTORY_PICTURES );
if ( isFilePathPrefixPresent( imageUri ) )
{
file = new File( imageUri );
}
else
{
file = new File( "file://" + imageUri );
}
filename = file.getName();
file = new File( dir, filename );
if ( file.exists() )
{
try
{
file.delete();
}
catch ( Exception e )
{
throw new IllegalStateException( "File wasn't deleted" );
}
}
else
{
throw new IllegalStateException( "File was doesn't exist" );
}
}
Related
I'm trying to do 2 actions from Google Drive with Google Apps Scripts :
Creating a file from a Google Doc template and insert data inside this file
Doing an export of this Google Doc file to PDF file inside Google Drive (at the same)
Step 1 is working : the Google Docs file is correclty created with values updated inside it.
Step 2 : I have 2 questions/problems :
The code I have found to generate PDF has been made to convert all Google Docs files to PDF files but from my side, I need just to export/convert the file which has been created (not all the files already located in the folder).
Despite of point 1, the script is working and PDF is generated but when I open the PDF file, the values added inside it have been lost, I have only the tags present in the template.
Have you got some ideas?
Here is the code :
function replaceTags () {
// Global vars
var ui = DocumentApp.getUi ();
var date = Utilities.formatDate(new Date(), "GMT", "dd-MM-yyyy");
var folderOutId = 'xxxxxxxxxxxxxxxxxxxx';
var tplMaintenanceId = 'xxxxxxxxxxxxxxxxxxxx';
var fileOutName = 'my file name';
var clientCompany = ui.prompt ('Company Name :');
// Do a copy from template file to a new file inside a specific folder
targetFolder = DriveApp.getFolderById (folderOutId);
var documentId = DriveApp.getFileById (tplMaintenanceId). makeCopy (targetFolder). getId ();
// Rename filed copied
DriveApp.getFileById (documentId) .setName (fileOutName + ' - ' + clientCompany.getResponseText ());
// Add document body inside variable
var body = DocumentApp.openById (documentId) .getBody ();
// Insert data inside Google Doc document
body.replaceText ('##DATE##', date);
body.replaceText ('##CLIENT_COMPANY##', clientCompany.getResponseText ());
gdocToPDF(documentId);
}
function gdocToPDF(fileID) {
var documentRootfolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx") // replace this with the ID of the folder that contains the documents you want to convert
var pdfFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxx"); // replace this with the ID of the folder that the PDFs should be put in.
var docFile = DriveApp.getFileById(fileID)
createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
if (fileID) createPDFfile(fileID, folderID);
}
)
}
function createPDF(fileID, folderID, callback) {
var templateFile = DriveApp.getFileById(fileID);
var templateName = templateFile.getName();
var existingPDFs = DriveApp.getFolderById(folderID).getFiles();
//in case no files exist
if (!existingPDFs.hasNext()) {
return callback(fileID, folderID);
}
for (; existingPDFs.hasNext();) {
var existingPDFfile = existingPDFs.next();
var existingPDFfileName = existingPDFfile.getName();
if (existingPDFfileName == templateName + ".pdf") {
Logger.log("PDF exists already. No PDF created")
return callback();
}
if (!existingPDFs.hasNext()) {
Logger.log("PDF is created")
return callback(fileID, folderID)
}
}
}
function createPDFfile(fileID, folderID) {
var templateFile = DriveApp.getFileById(fileID);
var folder = DriveApp.getFolderById(folderID);
var theBlob = templateFile.getBlob().getAs('application/pdf');
var newPDFFile = folder.createFile(theBlob);
var fileName = templateFile.getName().replace(".", ""); //otherwise filename will be shortened after full stop
newPDFFile.setName(fileName + ".pdf");
}
I tried recreating your code and I converted a doc to pdf successfully.
What you can do to is to edit your gdocToPDF() function to accept only the document that you want to be converted to PDF. Please see below sample code(might not be exactly the way you want it):
Pass the document id used in replaceTags() function to gdocToPDF()
function replaceTags () {
....
....
DocumentApp.openById(documentId).saveAndClose()
gdocToPDF(documentId);
}
Instead of fetching all the files in a drive folder, use this code instead to use the file with replaced tags only
function gdocToPDF(fileID) {
var documentRootfolder = DriveApp.getFolderById(folder-id) // replace this with the ID of the folder that contains the documents you want to convert
var pdfFolder = DriveApp.getFolderById(folder-id); // replace this with the ID of the folder that the PDFs should be put in.
var docFile = DriveApp.getFileById(fileID)
createPDF(docFile.getId(), pdfFolder.getId(), function (fileID, folderID) {
if (fileID) createPDFfile(fileID, folderID);
}
)
}
This will make a doc to pdf conversion to the only document that you wanted to be converted.
Have a great day ahead!
[HttpPost("FilePost")]
public async Task<IActionResult> FilePost(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
var filePath = Directory.GetCurrentDirectory() + "/files";
if (!System.IO.Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
foreach (var item in files)
{
if (item.Length > 0)
{
using (var stream = new FileStream(filePath,FileMode.CreateNew))
{
await item.CopyToAsync(stream);
}
}
}
return Ok(new { count = files.Count, size, filePath });
}
FormFile. FileName = directory + filename,
Uploaded file, file name with path information, how to do?
I just need to get the name of the file.
I just need to get the name of the file.
Use Path.GetFileName() to get the name of the file , and use Path.Combine() to combine the the save path you want with the file name , try the code like below
var filesPath = Directory.GetCurrentDirectory() + "/files";
if (!System.IO.Directory.Exists(filesPath))
{
Directory.CreateDirectory(filesPath);
}
foreach (var item in files)
{
if (item.Length > 0)
{
var fileName = Path.GetFileName(item.FileName);
var filePath = Path.Combine(filesPath, fileName);
using (var stream = new FileStream(filesPath, FileMode.CreateNew))
{
await item.CopyToAsync(stream);
}
}
}
Seem like you want to get the file name base on your file path.
You can get it into way
using System.IO;
Path.GetFileName(filePath);
or extension method
public static string GetFilename(this IFormFile file)
{
return ContentDispositionHeaderValue.Parse(
file.ContentDisposition).FileName.ToString().Trim('"');
}
Please let me know if you need any help
I faced the same issue with different browsers. IE send FileName with full path and Chrome send only the file name. I used Path.GetFileName() to overcome issue.
Other fix is at your front end side. Refer this to solve from it front end side.
I am developing a plugin using org.sonarsource.sonarqube:sonar-plugin-api:6.3. I am trying to access a file in my resource folder. The reading works fine in unit testing, but when it is deployed as a jar into sonarqube, it couldn't locate the file.
For example, I have the file Something.txt in src/main/resources. Then, I have the following code
private static final String FILENAME = "Something.txt";
String template = FileUtils.readFile(FILENAME);
where FileUtils.readFile would look like
public String readFile(String filePath) {
try {
return readAsStream(filePath);
} catch (IOException ioException) {
LOGGER.error("Error reading file {}, {}", filePath, ioException.getMessage());
return null;
}
}
private String readAsStream(String filePath) throws IOException {
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
if (inputStream == null) {
throw new IOException(filePath + " is not found");
} else {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
}
This question is similar with reading a resource file from within a jar. I also have tried with /Something.txt and Something.txt, both does not work.If I put the file Something.txt in the classes folder in sonarqube installation folder, the code will work.
Try this:
File file = new File(getClass().getResource("/Something.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
String something = IOUtils.toString(reader);
Your should not use getContextClassLoader(). see Short answer: never use the context class loader!
Hi i'am using this utils, to make file upload and delete upload. MVC 4 LINQ to SQL.
I would like to check if file is already uploaded, and if, make a meassage
to try new file.
Can you help me, getting started, to add code for this ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CFire2.SupplyConUtils
{
public static class FileUpload
{
public static char DirSeparator =
System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = "Content" +
DirSeparator + "SupplyUpload" + DirSeparator;
public static string UploadFile(HttpPostedFileBase file)
{
// Check if we have a file
if (null == file) return "";
// Make sure the file has content
if (!(file.ContentLength > 0)) return "";
string fileName = file.FileName;
string fileExt = Path.GetExtension(file.FileName);
// Make sure we were able to determine a proper
// extension
if (null == fileExt) return "";
// Check if the directory we are saving to exists
if (!Directory.Exists(FilesPath))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(FilesPath);
}
//// Set our full path for saving
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Save our file
file.SaveAs(path);
// Return the filename
return fileName;
}
public static void DeleteFile(string fileName)
{
// Don't do anything if there is no name
if (fileName.Length == 0) return;
// Set our full path for deleting
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Check if our file exists
if (File.Exists(path))
{
// Delete our file
File.Delete(path);
}
}
}
}
The MSDN docs for HttpPostedFileBase.FileName says
When overridden in a derived class, gets the fully qualified name of
the file on the client.
So probably you need to add this line to correctly execute your check
string fileName = Path.GetFileName(file.FileName);
and then
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"),
fileName);
if(File.Exists(path))
return "The file has been already uploaded!
....
I am using Play Framework 2.0.4. Here is my code that I have tried :
public static Result save() throws FileNotFoundException {
Form<Tenant> tenantForm = form(Tenant.class).bindFromRequest();
Form<Ten> tenForm = form(Ten.class).bindFromRequest();
Long tenantid = tenForm.get().tenant_id;
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart picture = body.getFile("logo_url");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
tenantForm.get().logo_url = file.getPath();
tenantForm.get().save();
return redirect(
routes.Application.index()
);
} else {
flash("error", "Missing file");
return redirect(
routes.Project.ctstenant(0,"name","asc","","",tenantid)
);
}
}
It will stores the image in temp folder. I want it to store in a specified folder. With the example will be appreciated.
Thanks for the help.
You can move your file from TEMP folder to your file storage directory. Below is the example how to move your uploaded file :
// define file storage path
public static final String fileStoragePath = "D:\\filestorage\\";
// handle form submit action
public static Result save() {
// bind request logic
...
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
// log message to console
Logger.info("Original file name = " + fileName +
" with Content Type " + contentType);
// Rename or move the file to the storage directory
if (file.renameTo(new File(fileStoragePath + fileName))) {
Logger.info("Success moving file to " + file.getAbsolutePath());
} else {
Logger.info("Failed moving file on " + file.getAbsolutePath());
}
// save your file name or using blob (it is your choice)
...
}
}
Note that, path defined on fileStoragePath must be available before to successfully moving or renaming the uploaded file.