Image saving do not work if name contain slash - android

I developing app which send images to server. All image name must begin with scanned code (barcode or QR code) + 5 random numbers.
Everthing works fine if i scan barcode with numbers. But if i scan QR code wich contain slash character / then my app explode.
if I parse scanned QR code and replace / with _ again everything works fine.
This is code where i generate image file
private File createImageFile() throws IOException {
imageName = generateImageName();
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageName, ".png", storageDir);
mCurrentPhotoPath = image.getPath();
mImageNameList.add(imageName);
return image;
}
This is code where i generate image name. Part with replacing characters can be commented.
public String generateImageName() {
int randomNumber = randomGenerator.nextInt((99999 - 100) + 1) + 100;
// Image name generator
if (mCodeContent.contains("http://")) {
mCodeContent = mCodeContent.replace("http://", "");
}
if (mCodeContent.contains("/")) {
mCodeContent = mCodeContent.replace("/", "_");
}
imageName = mCodeContent + "_" + Integer.toString(randomNumber) + ".png";
return imageName;
}
i need full QR code name with slashes

In my opinion it is bad idea to use slashes in filename, because Linux and Android filesystem doesn't allow to use this characters in filename. It may cause serious problems on server side too.
I think that server requirements should be changed in this case.

File name contains slash / is raising exception because this char is reserved for directory, may be replace with Character 'DIVISION SLASH' (U+2215) which looks like ∕, or Character 'FULLWIDTH SOLIDUS' (U+FF0F) which looks like /.

In my opinion you don't actually NEED to name your images with the url of the QR in the first place, that's just the way you designed your solution, but your initial problem probably never involved that by itself.
On top of that you didn't take into account any https:// beginning in your code.
To stay on your request :
Why you can't do it :
"/" is the character to separate folders in the paths of your filesystem, you can't put any in a filename.
What you could do with minimal changes :
encode the url so you don't get "/" but "%2F"

Related

Processing Android: java.lang.IllegalArgumentException: File contains a path sepator

Im currently trying to save some values in a text file in Processing Android (APDE). I want to later use this in another context, so it's important to use a complete file path. From Processing documentation for loadStrings():
... Alternatively, the file maybe be loaded from anywhere on the local
computer using an absolute path (something that starts with / on Unix
and Linux, or a drive letter on Windows)
So it must be possible.
I already searched for a answer, but never found something for Processing.
So my code is:
String[] saveData;
int score;
void setup(){
saveData=loadStrings("/storage/emulated/0/dataP/hi.txt");
score=parseInt(saveData[0]);
fullScreen();
frameRate(60);
noStroke();
noSmooth();
textAlign(CENTER);
textSize(height/20);
}
void draw(){
background(0);
fill(255) ;
text(score, width/2,height/2);
}
void mousePressed(){
score--;
saveData[0]=str(score);
println(saveData[0]);
saveStrings("/storage/emulated/0/hi.txt" ,saveData);
}
and I get the following error:
java.lang.IllegalArgumentException: File
/storage/emulated/0/dataP/hi.txt contains a path separator
I believe the confusion stems from the fact that loadStrings() method works differently for Java mode and Android mode. In Java mode, it is definitely possible to give loadStrings() an absolute Path with included separators, but in Android mode, loadStrings() will only work if you only specify a name without any separator (assumes by default to be looking into the data folder). Therefore, having any separator inside loadStrings() will throw the error.
One simple workaround you can try is to first create a separate path variable:
String path = "/storage/emulated/0/dataP/hi.txt";
And then give that as parameter to the loadStrings() method:
saveData = loadStrings(path);
If you were to use an SD card for storage, for example, you could do something like:
String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(SDCARD + File.separator + "mytext.txt");
String[] s = loadStrings(file.getPath());
As explained in the link in the comment I posted, loadStrings() and saveStrings() does not take absolute path as argument. What it means is that it can only access files with path "name.txt" and not "folder/name.txt". You have to do it using a FileInputStream and FileOutputStream if you must use absolute path. There are many examples of both these files on StackOverflow.

Image File Saved on Android Device Not Opening

I need to display an image and some HTML associated with it in a WebView. I get the image as byte[]. I am creating a .PNG file using the following code.
private string CreatePNG(byte[] data)
{
string filePath = Android.OS.Environment.ExternalStorageDirectory.Path;
string fileName = System.Guid.NewGuid().ToString() + ".png";
File.WriteAllBytes(Path.Combine(filePath, fileName), data);
return Path.Combine(filePath, fileName);
}
Then I embed the .PNG file in my HTML using the following code.
html += #"<img src=""file://" + CreatePNG(page.DocumentImage) + "\"/><br><br>";
The image shows as blank in my app. The text shows properly. If I try to open the image directly on the phone after browsing from "File Manager", it still shows as blank. When I copy the image from the phone to my Mac, it opens up fine.
Can someone please advise what is going wrong here?

How to Write float data into Text file in Android Working with Unity and C#

im trying to Write the data Stored in a float variable into a text file.
it works well in PC using Streamwriter
using (System.IO.StreamWriter file = new System.IO.StreamWriter();
but not on Android.
please tell me what is the way to Write it into a text file .
all i need is a similar way to write the above which works on android as well.
*collecting data from leap motion
*each frame data has to be written into Text file.
There's lots of good resources in the Unity documentation/forums for this. Look up 'Unity File I/O' and you will find links to articles that are helpful.
Here's some sample code to help you with your specific problem:
public void WriteToFile()
{
string FILE_PATH = Application.persistentDataPath + "/MYFILENAME.txt";
if (File.Exists(FILE_PATH))
{
Debug.Log(FILE_PATH + " already exists.");
return;
}
StreamWriter sr = System.IO.File.CreateText(FILE_PATH);
sr.WriteLine ("This is line 1 to be written in file.");
sr.WriteLine ("This is line 2.");
sr.Close();
}
I hope that helps!

How to serve dynamic pdf in Django on mobile device

Using pdftk I generate some dynamic temporary pdf files, which then Django serves to the user.
On a desktop, it works fine - the pdf file opens which then user can save, however on my android phone in all browsers (maybe the same on iOS but don't have and iOS device so can't test), the pdf does not download successfully. It starts the download but then always fails and I can't figure out why.
The following is a snippet of the view and the function which generates the pdf binary data:
def get_pdf():
fdf = {...}
t1 = tempfile.NamedTemporaryFile(delete=False)
t2 = tempfile.NamedTemporaryFile(delete=False)
t1.file.write(fdf)
# close temp files for pdftk to work properly
t1.close()
t2.close()
p = Popen('pdftk %s fill_form %s output %s flatten' %
('original.pdf', t1.name, t2.name), shell=True)
p.wait()
with open(t2.name, 'rb') as fid:
data = fid.read()
# delete t1 and t2 since they are temp files
# at this point the data is the binary of the pdf
return data
def get_pdf(request):
pdf = get_pdf()
response = HttpResponse(pdf, mimetype='application/pdf')
response['Content-Disposition'] = 'filename=foofile.pdf'
return response
Any ideas as to why this might be happening?
As per #Pascal comment, I added Content-Length and the downloads now work on mobile devices.
However it was not being downloaded with the filename I assign it in the view. Adding attachment fixes this but I don't want the attachment to be present for desktop browsers. Hence the following is my final solution which works.
# I am using the decorator from http://code.google.com/p/minidetector/
#detect_mobile
def event_pdf(request, event_id, variant_id):
pdf = get_pdf()
response = HttpResponse(pdf, mimetype='application/pdf')
response['Content-Disposition'] = '%sfilename=foofile.pdf' %
request.mobile and 'attachment; ' or ''
response['Content-Length'] = len(pdf)
return response

Display .mht file on android

How to display .mht(MHTML) file on android webview. I tried to open the .mht file on default android browser but that didn't open but i am able to open same on opera mobile browser. So i tried with MHTUnpack java library. I didn't succeed in that.
Here's a link!
Please if anybody has used this MHTUnpack let me how can i use that in android. And also let me know if there is any other library.
Thanks
Found this unknown google project which appears to be working.
This utility decodes the mhtml file and save it on given path(internal or external). After saving it returns the html file path which could be loaded into webview.
Try it.
After overcoming frustration about WebView.saveWebArchive() format change in Android 4.4, I tried the "unknown google project" Chitranshu Asthana mentioned in his answer, but code provided there is slow (~10s for 1MB *.mht file with a dozen of pictures) and doesn't handle attached file names correctly.
MHT Unpack library combined with Java Mail for Android (not the one provided by Oracle) worked perfectly for me.
EDIT: Fixed the link to MHT Unpack library. Also, here's usage example:
// contentPath - path to input .mht file
public static String unpackMht(String contentPath) throws IOException {
// dstPath - path where file will be unpacked
String dstPath = openTempDir(null) + File.separator;
String indexFileName = dstPath + new File(contentPath).getName();
try {
Collection<Attachment> attachments = MHTUnpack.unpack(new File(contentPath));
for (Attachment attachment : attachments) {
String filename = attachment.getFileName();
String path = filename == null ? indexFileName : dstPath + filename;
File newFile = new File(path);
if (newFile.exists()) {
newFile.delete();
}
attachment.saveFile(path);
}
return indexFileName;
} catch (MessagingException e) {
throw new IOException(e);
}
}

Categories

Resources