save image file in specific directory jsf primefaces project - file-upload

I want to save byte[] file into a specific directory :
I get it from this method :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
}
and I access the byte[] with :
uploadedPicture.getContents()
I tested this link but no result
how to save it into a specific directory either inside my project or outside
thank you
*********EDIT**********
here is the code whic works but sometimes I have the error :
public void setUploadedPicture(UploadedFile uploadedPicture)
{
System.out.println("set : "+uploadedPicture.getFileName()+" size : "+uploadedPicture.getSize());
this.uploadedPicture = uploadedPicture;
InputStream inputStr = null;
try {
inputStr = uploadedPicture.getInputstream();
} catch (IOException e) {
e.printStackTrace();
}
//create destination File
String destPath = "C:\\"+uploadedPicture.getFileName();
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
e.printStackTrace();
}
}

public void handleFileUpload(FileUploadEvent event) {
//get uploaded file from the event
UploadedFile uploadedFile = (UploadedFile)event.getFile();
//create an InputStream from the uploaded file
InputStream inputStr = null;
try {
inputStr = uploadedFile.getInputstream();
} catch (IOException e) {
//log error
}
//create destination File
String destPath = "your path here";
File destFile = new File(destPath);
//use org.apache.commons.io.FileUtils to copy the File
try {
FileUtils.copyInputStreamToFile(inputStr, destFile);
} catch (IOException e) {
//log error
}
}

Related

Print PDF file using Xamarin forms

I am printing a Pdf file via print services.
I implemented some code but it's not working - it throws the exception:
java.lang.RuntimeException: Cannot print a malformed PDF file
Please check my code and let me where I am going wrong.
internal class CustomPrintDocumentAdapter : PrintDocumentAdapter
{
private string filePath;
public CustomPrintDocumentAdapter(string filePath)
{
this.filePath = filePath;
}
public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
{
if (cancellationSignal.IsCanceled)
{
callback.OnLayoutCancelled();
return;
}
callback.OnLayoutFinished(new PrintDocumentInfo.Builder(filePath)
.SetContentType(PrintContentType.Document)
.Build(), true);
}
public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
{
try
{
using (InputStream input = new FileInputStream(filePath))
{
using (OutputStream output = new FileOutputStream(destination.FileDescriptor))
{
var buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.Read(buf)) > 0)
{
output.Write(buf, 0, bytesRead);
}
}
}
callback.OnWriteFinished(new[] { PageRange.AllPages });
}
catch (FileNotFoundException fileNotFoundException)
{
System.Diagnostics.Debug.WriteLine(fileNotFoundException);
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine(exception);
}
}
}

Dropbox Java Api Upload File

How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}

Downloading a file from Google cloud storage is corrupted randomly

I am trying to download data Bigquery data through Google cloud storage. Am able to send data from BigQuery to GCS but when downloading data from GCS to load the files are corrupted randomly.
getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
out = fs.create(pathDir, true);
getObject.executeMediaAndDownloadTo(out);
boolean match= ismd5HashValid(o.getMd5Hash(), pathDir);
and to check md5 checksum
private boolean ismd5HashValid(String md5hash, String path) {
org.apache.hadoop.fs.Path pathDir = new org.apache.hadoop.fs.Path(path);
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
InputStream is = null;
try {
FileSystem fs = FileSystem.get(conf);
MessageDigest md = MessageDigest.getInstance("MD5");
is = fs.open(pathDir);
byte[] bytes = new byte[1024];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
md.update(bytes, 0, numBytes);
}
byte[] digest = md.digest();
String result = new String(Base64.encodeBase64(digest));
Log.info("Source file md5hash {} Downloaded file md5hash {}", md5hash, result);
if (md5hash.equals(result)) {
Log.info("md5hash check is valid");
return true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.warn(e.getMessage(), e);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
Log.warn(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
}
return false;
}

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

Error: file doesn't exist

Now am working on a project where I need to create a folder in sdcard which am able to do. Also I need to hide/unhide it according to need. The code is working fine on emulator but not in device this is my code what went wrong ?
public class FolderCreate extends MIDlet {
private Form form;
private Display display;
FileConnection fc;
String path;
public void startApp() {
form = new Form("Hello World");
String msg = "Hello World!!!!!!!";
form.append(msg);
display = Display.getDisplay(this);
display.setCurrent(form);
System.out.println("WWWW");
try {
path = System.getProperty("fileconn.dir.memorycard");
System.out.println("Path : "+path+"/sample");
fc = (FileConnection)Connector.open(path+"/ABCD/");
if(!fc.exists())
{
fc.mkdir();
System.out.println("directory created");
}
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("ERROR "+e.getMessage());
Alert alert = new Alert("Alert");
alert.setString(e.getMessage());
display.setCurrent(alert);
}
try
{
//fc = (FileConnection)Connector.open(path+"/sample/");
if(fc.isHidden())
{
fc.setHidden(false);
}
else{
fc.setHidden(true);
}
fc.close();
}
catch (Exception e)
{
Alert alert = new Alert("Alert2");
alert.setString(e.toString());
display.setCurrent(alert);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
System.out.println("Destroyed");
notifyDestroyed();
}
}
The error am getting is: java.io.IOException: file does not exist
Check if path starts with "file://". If not, add the suffix.
path = System.getProperty("fileconn.dir.memorycard");
if (path != null && !path.startsWith("file://")) {
path = "file://" + path;
}
I think you are doing mistake at following line,
path = System.getProperty("fileconn.dir.memorycard");
When you are working with phone and SD-Card you should use e: drive for referring to SD Card as follows,
path = file:///e:/<folder-name>/