Am trying to upload a pdf file to Google Docs/Drive,
For that am using the following code...
int MAX_CONCURRENT_UPLOADS = 10;
int PROGRESS_UPDATE_INTERVAL = 1000;
int DEFAULT_CHUNK_SIZE = 10485760;
ExecutorService executor = Executors.newFixedThreadPool(MAX_CONCURRENT_UPLOADS);
File file = new File(filePath);
String mimeType=DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
String contentType=DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
MediaFileSource mediaFile = new MediaFileSource(file, contentType);
URL createUploadUrl = new URL("https://drive.google.com/feeds/upload/create-session/default/private/full");
FileUploadProgressListener listener = new FileUploadProgressListener();
ResumableGDataFileUploader uploader=new ResumableGDataFileUploader(createUploadUrl,mediaFile,service, DEFAULT_CHUNK_SIZE, executor, listener, PROGRESS_UPDATE_INTERVAL);
But FileUploadProgressListener showing error, It is a google api or a class...?
Please help what am wrong to upload a pdf file....
Thanks in advance
You are using Google's older API. Try the new Google Drive API
Reference :
https://developers.google.com/drive/
http://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples&r=08555cd2a27be66dc97505e15c60853f47d84b5a
Related
This is the qr-code generator, I put on String qrCodeData to try access the storage of my phone and open up a file, but it doesnt work. Turns out the generated qr code only gives the link.
public class QRCode {
public static void main(String[] args) {
try {
String qrCodeData = "Device storage/Download/japanese/Mastering_Kanji_1500.pdf";
String filePath = "D:\\QR code project\\Generated QR codes\\qr.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix matrix = new MultiFormatWriter().encode(
new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, 200, 200, hintMap);
MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
.lastIndexOf('.') + 1), new File(filePath));
System.out.println("QR Code image created successfully! and stored at location"+filePath);
} catch (Exception e) {
System.err.println(e);
}
}
}
We are able to view and manipulate PDF files via the PDFBox library.
Android version.
We may also use MuPDF. It has an Android version.
Interpret the received link as a file or download it to storage, then proceed to interface with PDFBox library.
Note that file downloading and access on Android should now be done via Room interface or SQLite as recommended by Google.
Hope this helps.
I want to download a file in my telegram bot code many tutorials say that I must use the getFile method that I can't find that in 4.2 version of the telegram API
so how I can download a file to a specific destination in host pc?
thanks
Assuming you are using TelegramBot SDK from rubenlagus (https://github.com/rubenlagus/TelegramBots), as I faced same issue. Below is my solution.
GetFile getFile = new GetFile().setFileId(fileId);
String filePath = execute(getFile).getFilePath();
File file = downloadFile(filePath, outputFile);
I had the same problem.
This was my solution. Not very nice but it works.
if (update.getMessage().hasDocument()){
String doc_id = update.getMessage().getDocument().getFileId();
String doc_name = update.getMessage().getDocument().getFileName();
String doc_mine = update.getMessage().getDocument().getMimeType();
int doc_size = update.getMessage().getDocument().getFileSize();
String getID = String.valueOf(update.getMessage().getFrom().getId());
Document document = new Document();
document.setMimeType(doc_mine);
document.setFileName(doc_name);
document.setFileSize(doc_size);
document.setFileId(doc_id);
GetFile getFile = new GetFile();
getFile.setFileId(document.getFileId());
try {
org.telegram.telegrambots.meta.api.objects.File file = execute(getFile);
downloadFile(file, new File("./data/userDoc/"+getID+"_"+doc_name));
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
Here I got this solution
enter link description here
I am looking into the PDF renderer API native to Google Android development. I see the following code example in the documentation:
// create a new renderer
PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());
// let us just render all pages
final int pageCount = renderer.getPageCount();
for (int i = 0; i < pageCount; i++) {
Page page = renderer.openPage(i);
// say we render for showing on the screen
page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);
// do stuff with the bitmap
// close the page
page.close();
}
// close the renderer
renderer.close();
I think this example uses from File Object. How I can get this API to work with a URL from a webserver, such as a document from a website? How can I load a PDF natively in an Android app that does not require a download of the file onto the local storage? Something like how you can run the Google docs viewer to open the PDF in webview - but I cannot take that approach because the Google docs viewer is blocked in the environment I am in.
You cannot use Pdf Renderer to load URL. But your can make use of Google Docs in your webview to load URL without downloading the file...
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=" + YOUR_URL);
how I can get this API to work with URL from a webserver?
Download the PDF from the server to a local file. Then, use the local file.
The purpose of what I am trying to learn is how to load pdf natively in android app that does not require a download of the file onto the local storage
AFAIK, you cannot use PdfRenderer that way. It needs a seekable FileDescriptor, and the only way that I know of to create one of those involves a local file.
I would first download the pdf and then show it in a pdfView
private fun downloadPdf(): File? {
val client = OkHttpClient()
val request = Request.Builder().url(urlString)
.addHeader("Content-Type", "application/json")
.build()
val response = client.newCall(request).execute()
val inputStream: InputStream? = response.body?.byteStream()
val pdfFile = File.createTempFile("myFile", ".pdf", cacheDir)
inputStream?.readBytes()?.let { pdfFile.writeBytes(it) }
return pdfFile
}
and then do something like this:
CoroutineScope(IO).launch {
val pdfDownloaded = downloadPdf()
if (pdfDownloaded != null) {
pdfView.fromFile(pdfDownloaded)
}
withContext(Main) {
pdfView.visibility = View.VISIBLE
hideProgress()
pdfView.show()
}
}
here
I am having a pdf file (Or any kinda file) byte array(coming through web service), which i want to display inside my Android application without getting it downloaded in the memory(Internal/External). I want to support it upto 30MB.
Same feature is getting used by Gmail App, where they are asking for Preview/Save.
Thanking you in advance.
You can check a pdf viewer that's working well in this case, it's name is RadaeePDF
To open a pdf from remote url:
Global.Init( this );
PDFHttpStream m_stream = new PDFHttpStream();
Document m_doc = new Document();
ReaderController m_vPDF = new ReaderController(this);
m_doc.Close();
m_stream.open("http://server/filename.pdf");
int ret = m_doc.OpenStream(m_stream, null);
if( ret == 0 ) {
m_vPDF.open(m_doc);
setContentView( m_vPDF );
}
I am having trouble with this code,
#Path("/play")
public class Player {
#GET
#Produces("audio/mpeg")
public Response get(#DefaultValue("C:\\Users\\Ben\\Music\\sample.mp3") #QueryParam("file") String file) {
File song = new File(file);
return Response.ok().entity(song).build();
}
}
Chrome is able to play the content returned from this, but Safari mobile can't.
When I move the sample.mp3 into static web folder it is able to play in Safari mobile browser.
How can I get mobile Safari to play audio returned using JAX-RS?
I used the AudioAttributes and EncodingAttributes classes to convert the file to the right codec. It's pretty slow and wastes a lot of storage because a new file has to be create each time a song is played. I'll probably change this code later so that the files are cached after converted. Then before I convert I check if I already converted. Also it would be nice to test if the raw file is compatible with the device before converting it. Here's current the code.
#GET
#Path("/audio")
#Produces("audio/mpeg")
public Response getAudio(
#DefaultValue("C:\\Users\\Ben\\Music\\sample.mp3") #QueryParam("file") String file,
#DefaultValue("medium") #QueryParam("quality") String quality) throws EncoderException, IOException {
File song = new File(file);
File rootMusicDir = new File(AUDIO_PATH);
File rootVideoDir = new File(VIDEO_PATH);
if (!directoryService.isSubDirectory(rootMusicDir, song) && !directoryService.isSubDirectory(rootVideoDir, song)) {
return Response.status(500).build();
}
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
if (quality.equalsIgnoreCase("high")) {
audio.setBitRate(new Integer(256000));
audio.setChannels(new Integer(2));
audio.setSamplingRate(new Integer(44100));
} else if (quality.equalsIgnoreCase("medium")) {
audio.setBitRate(new Integer(128000));
audio.setChannels(new Integer(2));
audio.setSamplingRate(new Integer(44100));
} else {
audio.setBitRate(new Integer(64000));
audio.setChannels(new Integer(1));
audio.setSamplingRate(new Integer(22050));
}
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
Encoder encoder = new Encoder();
String random = new BigInteger(130, new SecureRandom()).toString(32);
File songMP4 = new File(TEMP_PATH + file.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+") + random);
encoder.encode(song, songMP4, attrs);
return Response.ok().entity(songMP4).build();
}
Could you clarify what the root cause of your problem was? I don't quite follow why re-encoding the file should solve the problem? From what I understood, you have an .mp3 which works fine in Safari mobile when served statically, but not when served as per your code above. I presume, therefore, that your original .mp3 is encoded in a fashion that iOS can cope with (or else the statically served file would not play correctly).
Could there be an issue with the headers that you are sending along with the served .mp3? The reason I ask is that I have a similar problem serving an mp3 to mobile Safari which is served by a Perl script. Works fine when files statically served. When the same file is served using Perl it gives 404 in Safari mobile (Safari on OSX works fine).