Improvements in uploading of files, vaadin - vaadin

I want to upload file to git without saving on local disk. I use vaadin + java in my webapp, and upload component from vaadin.
public OutputStream receiveUpload(String filename, String MIMEType)
{
this.filename = filename;
FileOutputStream fos = null;
try {
// exist any possibility to no saving file in filepath (only push
// to git)
fos = new FileOutputStream(new File(
filepath + File.separator + filename));
} catch (Exception e) {
// How to omit it, I don't want to save file in filepath...
return null;
}
return fos;
}
public void uploadSucceeded(Upload.SucceededEvent event)
{
try {
// this method read file from filepath. Exist any possibilty to
// transfer file from upload panel to here without saving this
// file in filepath ?
commitToGit(filepath + File.separator + filename);
} catch(Exception e) {
e.printStackTrace();
} finally {
// removing file from filepath, it is no comfortable for me
File file = new File(filepath + File.separator + filename);
if (file != null) {
file.delete();
}
}
}

Look here for the pipe functionality
Best way to Pipe InputStream to OutputStream
in the receiveUpload method you setup the pipe between the uploading file and your git connector.
The uploadSucceeded method is then not needed or can be used to cleanup resources.

Related

The problem of FormDataContentDisposition in Jersey File Upload

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/files")
public class FileUploadService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces({"text/plain","application/xml","application/json"})
public Response uploadPdfFile( #FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
//String UPLOAD_PATH = "f://";
String UPLOAD_PATH = "c://temp//";
try
{
int read = 0;
byte[] bytes = new byte[102400];
OutputStream out = new FileOutputStream(new File(UPLOAD_PATH +
fileMetaData.getFileName()));
//OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + "xx.txt"));
while ((read = fileInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e)
{
throw new WebApplicationException("Error while uploading file. Please try again !!");
}
return Response.ok("Data uploaded successfully !!").build();
}
}
A code of Jersey upload was running. If I use OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + "xx.txt")), it is good and I can see the xx.txt file in c:\temp folder.
However, if I use OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName())), it said Data uploaded successfuly!!, but I cannot see anything in c:\temp folder.
Did this FormDataContentDisposition have any bug? Or I use it in wrong way?
The line "return Response.ok("Data uploaded successfully !!").build();" will return "Data uploaded successfully !!".
However, if I change the line "return Response.ok("Data uploaded successfully !!").build(); to return Response.ok("Data uploaded successfully !!"+fileMetaData.getFileName()).build();
I got the results of "Data uploaded successfully !!C:CodingWeb services16.JAX-RS File Upload Exampletest.txt".
Why did fileMetaData.getFileName() return "C:CodingWeb services16.JAX-RS File Upload Exampletest.txt"?

ASP.net MVC Database backup

I need to backup my database and I want to get that file as a download file. Simply when you get some kind of file from any website, they are just downloaded. I want to backup my database without setting a directory to that.
sqlcmd = new SqlCommand("backup database test to disk='" + backupDIR + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", con);
In this coding it sets a backup directory. I want to get that file as a downloaded file via browser.
How can this be achieved?
Try this
public FileResult Download()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(#"c:\folder\myfile.ext");
string fileName = "myfile.ext";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
From here
public ActionResult Backup()
{
BackupDB db = new BackupDB();
if (db.BackupDatabase())
{
ViewData["Success"] = "Backup is completed Successfully";
Download("09062016_200840.Bak");
return View("AdminIndex");
}
ViewData["Exception"] = "Backup Failed";
return View("AdminIndex");
}
public FileResult Download(string ImageName)
{
return File("‪C:\\Backups" + ImageName,System.Net.Mime.MediaTypeNames.Application.Octet);
}

How to send HttpPostedFileBase to S3 via AWS SDK

I'm having some trouble getting uploaded files to save to S3. My first attempt was:
Result SaveFile(System.Web.HttpPostedFileBase file, string path)
{
//Keys are in web.config
var t = new Amazon.S3.Transfer.TransferUtility(Amazon.RegionEndpoint.USWest2);
try
{
t.Upload(new Amazon.S3.Transfer.TransferUtilityUploadRequest
{
BucketName = Bucket,
InputStream = file.InputStream,
Key = path
});
}
catch (Exception ex)
{
return Result.FailResult(ex.Message);
}
return Result.SuccessResult();
}
This throws an exception with the message: "The request signature we calculated does not match the signature you provided. Check your key and signing method." I also tried copying file.InputStream to a MemoryStream, then uploading that, with the same error.
If I set the InputStream to:
new FileStream(#"c:\folder\file.txt", FileMode.Open)
then the file uploads fine. Do I really need to save the file to disk before uploading it?
This is my working version first the upload method:
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
request.WithBucketName(_bucketName)
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey(filePath).InputStream = inputStream;
request.AddHeaders(AmazonS3Util.CreateHeaderEntry("ContentType", contentType));
_amazonS3Client.PutObject(request);
}
catch (Exception exception)
{
// log or throw;
return false;
}
return true;
}
I just get the stream from HttpPostedFileBase.InputStream
(Note, this is on an older version of the Api, the WithBucketName syntax is no longer supported, but just set the properties directly)
Following the comment of shenku, for newer versions of SDK.
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
string _bucketName = "";
request.BucketName = _bucketName;
request.CannedACL = S3CannedACL.PublicRead;
request.InputStream = inputStream;
request.Key = filePath;
request.Headers.ContentType = contentType;
PutObjectResponse response = _amazonS3Client.PutObject(request);
return true;
}catch(Exception ex)
{
return false;
}
}

How to compress the files in Blackberry?

In my application I used html template and images for browser field and saved in the sdcard . Now I want to compress that html,image files and send to the PHP server. How can I compress that files and send to server? Provide me some samples that may help lot.
i tried this way... my code is
EDIT:
private void zipthefile() {
String out_path = "file:///SDCard/" + "newtemplate.zip";
String in_path = "file:///SDCard/" + "newtemplate.html";
InputStream inputStream = null;
GZIPOutputStream os = null;
try {
FileConnection fileConnection = (FileConnection) Connector
.open(in_path);//read the file from path
if (fileConnection.exists()) {
inputStream = fileConnection.openInputStream();
}
byte[] buffer = new byte[1024];
FileConnection path = (FileConnection) Connector
.open(out_path,
Connector.READ_WRITE);//create the out put file path
if (!path.exists()) {
path.create();
}
os = new GZIPOutputStream(path.openOutputStream());// for create the gzip file
int c;
while ((c = inputStream.read()) != -1) {
os.write(c);
}
} catch (Exception e) {
Dialog.alert("" + e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
}
}
this code working fine for single file but i want to compress all the file(more the one file)in the folder .
In case you are not familiar with them, I can tell you that in Java the stream classes follow the Decorator Pattern. These are meant to be piped to other streams to perform additional tasks. For instance, a FileOutputStream allows you to write bytes to a file, if you decorate it with a BufferedOutputStream then you get also buffering (big chunks of data are stored in RAM before being finally written to disc). Or if you decorate it with a GZIPOutputStream then you get also compression.
Example:
//To read compressed file:
InputStream is = new GZIPInputStream(new FileInputStream("full_compressed_file_path_here"));
//To write to a compressed file:
OutputStream os = new GZIPOutputStream(new FileOutputStream("full_compressed_file_path_here"));
This is a good tutorial covering basic I/O . Despite being written for JavaSE, you'll find it useful since most things work the same in BlackBerry.
In the API you have these classes available:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream
If you need to convert between streams and byte array use IOUtilities class or ByteArrayOutputStream and ByteArrayInputStream.

Save media files to Blackberry SD card

I am creating a multimedia app that allows the user to save wallpapers and ringtones. I know the path I need to save them to is "SDCard/BlackBerry/ringtones/file.mp3" (or "/pictures" for wallpapers). I have searched forums and post for a couple days and the only thing I found was how to write text files. For now, assume that the ringtones and pictures are saved in the projects resource folder. If you could provide any input, I would greatly appreciate it.
Saving anything should be about the same. Try something like this:
FileConnection fc;
try {
String fullFile = usedir + filename;
fc = (FileConnection) Connector.open(fullFile, Connector.READ_WRITE);
if (fc.exists()) {
Dialog.alert("file exists");
} else {
fc.create();
fileOS = fc.openOutputStream();
fileOS.write(raw_media_bytes, raw_offset, raw_length);
}
} catch (Exception x) {
Dialog.alert("file save error);
} finally {
try {
if (fileOS != null) {
fileOS.close();
}
if (fc != null) {
fc.close();
}
} catch (Exception y) {
}
}
usedir and filename are your path components, raw_media_bytes is your data, etc etc.
Thanks for your help cjp. Here is the code to saving a resource mp3 file to a sd card:
byte[] audioFile = null;
try {
Class cl = Class.forName("com.mycompany.myproject.myclass");
InputStream is = cl.getResourceAsStream("/" + audioClip);
audioFile = IOUtilities.streamToBytes(is);
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/" + audioClip, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(audioFile);
outStream.close();
fc.close();
Dialog.alert("Ringtone saved to BlackBerry SDcard.");
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
} catch (Exception e) {
Dialog.alert(e.toString());
}
As cjp pointed out, here is how to save an image resource to a SD card:
EncodedImage encImage = EncodedImage.getEncodedImageResource(file.jpg");
byte[] image = encImage.getData();
try {
// create folder as above (just change directory)
// create file as above (just change directory)
} catch(Exception e){}

Resources