I have a functionality for add attachment. When we attach any file, it is uploaded to FTP server. For viewing purpose, there is a link that shows the file content from FTP server within the browser itself. I can open the file after downloading it from FTP server but i don't want to download or save the file on local machine. is there any way to open the file from FTP server without downloading or saving it on local machine?
The code that i wrote.
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServerIp);
boolean connectionStatus = ftpClient.login(ftpServerUserName, ftpServerPassword);
if(connectionStatus){
log.info("Connected successfully.");
}
ftpClient.changeWorkingDirectory(ftpServerUploadPath);
fos = new FileOutputStream(fileName);
boolean result = ftpClient.retrieveFile(fileName, fos);
log.info("result==>"+result);
Here the result is coming as true while retrieving the file. but i am not able to display the file contents. Is there any way to achieve it?
Any help is appreciated. Thanks in advance.
I have solved the problem by using below code.
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServerIp);
boolean connectionStatus = ftpClient.login(ftpServerUserName, ftpServerPassword);
if(connectionStatus){
log.info("Connected successfully.");
}
ftpClient.changeWorkingDirectory(ftpServerUploadPath);
InputStream stream = ftpClient.retrieveFileStream(fileName);
int length = 0;
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType( fileName );
response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
byte[] bbuf = new byte[fileName.length()];
DataInputStream in = new DataInputStream(stream);
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
out.write(bbuf,0,length);
}
in.close();
out.flush();
out.close();
Related
Sorry if this seems like a dumb question, but I just start the ftp and webserver thing so I get a little bit confused about it, particularly about the InputStream, fileInputStream and outputStream etc this kind of concepts. So I try to extend the program I write called web server and make it act as a FTP client that request txt file only. So when request a text file (.txt) from within my web browser, the web server will not have a copy of this file. It will instantiate an FtpClient, retrieve the text file from your local FTP server and then send it back to your web browser as an HTTP response.
My code works fine for web server part, following is part of my code:
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
...
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
// skip over the method, which should be "GET"
tokens.nextToken();
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.1 200 OK" + CRLF;
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
}
// file doesn't exist
else {
// if the file requested is any type other than a text (.txt) file,
// report // error to the web client
if (!contentType(fileName).equalsIgnoreCase("text/plain")) {
statusLine = "404 Not Found" + CRLF;
contentTypeLine = "no content" + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>" + "<BODY>Not Found</BODY></HTML>";
} else {
String server = "127.0.0.1";
// else retrieve the text (.txt) file from your local FTP server
statusLine = "200 OK" + CRLF;
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
// create an instance of ftp client
FTPClient ftp = new FTPClient();
// connect to the ftp server
ftp.connect(server);
ftp.login(userName, password);
// retrieve the file from the ftp server, remember you need to
// // first upload this file to the ftp server under your user
// ftp directory
ftp.retrieveFile("/folder1/"+ fileName.substring(1), os);
// disconnect from ftp server
ftp.disconnect();
// assign input stream to read the recently ftp-downloaded file
fis = new FileInputStream(fileName);
}
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
os.close();
br.close();
socket.close();
where things get confusing is that in the ftp retrieve part, I don't know if I use the correct method and if I should using "os" the DataOutputStream as argument or something else. Not fully understand the input and output stream thing. what I'm sure is that I want to use
fis = new FileInputStream(fileName);
after I retrieve the file from ftp server.
So can anyone tell me what should I use in the retrieve part?
Thanks!
I want to download a pdf file when user clicks on button.For front end I am using JSF 2.
Actually I want to download pdf files download imageas shown in primefaces demo
pdf files are stored on my local tomcat's inside Root folder.
I am following in this way but it's giving me exception as
java.io.IOException: Server returned HTTP response code: 505 for
URL:
URL url;
URLConnection con;
DataInputStream dis;
FileOutputStream fos;
byte[] fileData;
try {
url = new URL("http://localhost:8080/html/pdf/sample.pdf"); //File download Location goes here
System.out.println("URL "+url.toString());
con = url.openConnection(); // open the url connection.
dis = new DataInputStream(con.getInputStream());
fileData = new byte[con.getContentLength()];
for (int q = 0; q < fileData.length; q++) {
fileData[q] = dis.readByte();
}
dis.close(); // close the data input stream
fos = new FileOutputStream(new File("/Users/sample.pdf")); //FILE Save Location goes here
fos.write(fileData); // write out the file we want to save.
fos.close(); // close the output stream writer
}
catch(Exception m) {
System.out.println(m);
}
Is I am providing wrong path? If yes what is the correct path to
download file from local systems tomcat folder as shown ?
I thing you forget to put port number 8080 OR 8052 or put your port number if you have changed.
put a specific path.it works
URL url;
URLConnection con;
DataInputStream dis;
FileOutputStream fos;
byte[] fileData;
try {
url = new URL("http://localhost:8052/Naveed_workingfiles/a.pdf"); //File download Location goes here
System.out.println("URL "+url.toString());
con = url.openConnection(); // open the url connection.
dis = new DataInputStream(con.getInputStream());
fileData = new byte[con.getContentLength()];
for (int q = 0; q < fileData.length; q++) {
fileData[q] = dis.readByte();
}
dis.close(); // close the data input stream
fos = new FileOutputStream(new File("C:/Documents and Settings/microsoft/My Documents/Downloads/sample.pdf")); //FILE Save Location goes here
fos.write(fileData); // write out the file we want to save.
fos.close(); // close the output stream writer
} catch(Exception m) {
System.out.println(m);
}
I was trying to write simple "FTP" program, but then suddenly an error occured. So this is a network with client and server and a server storages files uploaded from client, there is also a possibility to download files from server. But when I upload file it is saved in Server directory as an empty file, will someone help me find an error in code?
Here is Client
String nameOfFileToUp = fileFromFileChooser.getName();
System.out.println("fileChooserfile name= " + fileFromFileChooser.getName());
System.out.println("File path= " + fileFromFileChooser.getPath());
pw.println(nameOfFileToUp);
File sendFile = new File(fileFromFileChooser.getPath());
FileInputStream fis = new FileInputStream(sendFile);
int size =(int) fileFromFileChooser.length();
byte[] buffer = new byte[size+1];
int bytes = 0;
while((bytes = fis.read(buffer)) != -1)
{
out.write(buffer,0,bytes);
}
fis.close();
Where pw is PrintWriter,
And Server
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dops = new DataOutputStream(fos);
while(done)
{
fc = in.readLine();
if(fc == null)
{
done = false;
}
else
{
dops.writeChars(fc);
}
}
fos.close();
Can anyone help? Please
You need to flush/close the output stream.
Also, your server should not be reading by "line", it should be reading bytes (just like your client code).
I'm having a tough time figuring something out. (I'm pretty new to all this.)
I wrote this java pgm to ftp a large file to a destination server.
Here's the code (codes been modified a bit for display):
public static void ftpUpload(String path, String upfileName, String dirName) throws Exception
{
FTPClient client = new FTPClient();
client.addProtocolCommandListener((ProtocolCommandListener) new PrintCommandListener(new PrintWriter(System.out)));
client.enterLocalPassiveMode();
FileInputStream fis = null;
int reply;
try {
client.connect(ftpserver);
client.login(ftpuserid, ftppasswd);
reply = client.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
client.changeWorkingDirectory(ftpdirectoryName + "/" + dirName);
boolean mkDir = client.makeDirectory(getCurrentMMMYY().toLowerCase());
client.changeWorkingDirectory(getCurrentMMMYY().toLowerCase());
//Create an InputStream of the file to be uploaded
fis = new FileInputStream(path + upfileName);
//Store file to server
client.storeFile(upfileName, fis);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.logout();
//client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Something weird is happening on files I'm sending...
One of my files on the origination server is 82575786 in size, and when I ftp this file it almost sends the entire file. It actually sends 82574867. (missing 919)
Another file on the origination server is 717885, and when I ftp this file it almost sends the entire file. It actually sends 717522. (missing 363)
I pulled the log to see if something crashed, but it didn't show anything wrong with the transfer. Here are the 2 log entries showing the transfer.
[08/09/11 20:21:13:618 EDT] 00000043 SystemOut O 221-You have transferred 717522 bytes in 1 files.
221-You have transferred 82574867 bytes in 1 files.
Anyone's help would greatly be appreciated.
Thanks
Dan.
Are you transferring in ASCII mode instead of binary? ASCII mode converts CR/LF to LF and vice-versa depending on server and client settings.
Are you using Apache's FTP client? It says the default is ASCII, you could try setting BINARY_FILE_TYPE with setFileType:
client.setFileType(FTPClient.BINARY_FILE_TYPE);
To upload a binary File you have to use the FTP.BINARY_FILE_TYPE but is not enough.
You are using only an INPUT stream, and you need to use an outputstream too
I hope that this example will help you:
FTPClient client = new FTPClient();
client.connect("192.168.30.20");
client.login("pwd", "pwd");
client.setFileType(FTP.BINARY_FILE_TYPE);
String path_base = "/myPath/";
InputStream fis = new FileInputStream("A.pdf");
OutputStream os = client.storeFileStream(path_base+ "B.pdf");
byte buf[] = new byte[8192];
int bytesRead = fis.read(buf);
while (bytesRead != -1) {
os.write(buf, 0, bytesRead);
bytesRead = fis.read(buf);}
fis.close();
os.close();
client.completePendingCommand();
client.logout();
client.disconnect();
I have this little piece of code below which uploads a file in java, the code functions correctly however it hangs for a long time when opening the output stream.
// open file to upload
InputStream filein = new FileInputStream("/path/to/file.txt");
// connect to server
URL url = new URL("ftp://user:pass#host/dir/file.txt");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
// write file
// HANGS FROM HERE
OutputStream ftpout = urlConn.getOutputStream();
// TO HERE for about 22 seconds
byte[] data = new byte[1024];
int len = 0;
while((len = filein.read(data)) > 0) {
ftpout.write(data,0, len);
}
// close file
filein .close();
ftpout.close();
In this example the URLConnection.getOutputStream() method hangs for about 22 seconds before continuing as normal, the file is successfully uploaded. The file is only 4 bytes in this case, just a text file with the word 'test' in it and the code hangs before the upload commences so its not because its taking time to upload the file.
This is only happening when connecting to one server, when I try a different server its as fast I could hope for which leads me to think it is a server configuration issue in which case this question may be more suited to server fault, however if I upload from an FTP client (in my case FileZilla) it works fine so it could be there is something I can do with the code to fix this.
Any ideas?
I have solved the problem by switching to use the Commons Net FTPClient which does not apear to have the same problems which changes the code to this below.
InputStream filein = new FileInputStream(new File("/path/to/file.txt"));
// create url
FTPClient ftp = new FTPClient();
ftp.connect(host);
ftp.login(user, pass);
int reply = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return;
}
OutputStream ftpout = ftp.appendFileStream("text.txt");
// write file
byte[] data = new byte[1024];
int len = 0;
while((len = filein.read(data)) > 0) {
ftpout.write(data,0, len);
}
filein.close();
ftpout.close();
ftp.logout();