URL url = new URL("http://localhost:8080/Work/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C://abt.jpg");
fos.write(response1);
fos.close();
in this code there is some error in last 3 lines
SEVERE: Servlet.service() for servlet ImageDownloadServlet threw exception java.io.FileNotFoundException: C:/abt.jpg (No such file or directory)
How can I solve it?
String filePath = request.getParameter("action");
System.out.println(filePath);
// URL url = new
// URL("http://localhost:8080/Works/images/abt.jpg");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename=icon" + ".jpg");
URL url = new URL(filePath);
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
}
Try using File.pathSeparator instead of slash.
maybe try switching C:/abt.jpg to C:\\abt.jpg
("C://abt.jpg");
try reversing the slashes
("C:\\abt.jpg");
I looked up a example link to a FOS to C drive example, and the demo had them the other way.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException, MalformedURLException {
String filePath = request.getParameter("action");
// String filename = "abt.jpg";
System.out.println(filePath);
URL url = new URL("http://localhost:8080/Works/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/home/user/Downloads/abt.jpg");
fos.write(response1);
fos.close();
}
this image will be in download folder
Related
I am downloading few pdf and video file from the server and for that I am using InputStream to collect response but I want to know that which is better for my purpose InputStream or FileInputStream or BufferedInputStream ?
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile, fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
I am using this for downloading videos
void downloadFile(String vidN){
int downloadedSize = 0;
int totalSize = 0;
try {
// here vidN is the name of the file like bird.mp4
// here sitepath is the path of the file
URL url = new URL(sitepath+vidN);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "VideoNR2";
File RootFile = new File(RootDir);
RootFile.mkdir();
//create a new file, to save the downloaded file
File file = new File(RootDir,""+vidN);
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize = bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
}
}
I want to upload an image to FTP Server. Currently i am using JDeveloper 12c(12.1.3.0).
My Code:
private static final int BUFFER_SIZE = 4096;
public String fileUploadMethod(String imagePath){
String ftpUrl = "ftp://";
String host = "http://192.168.0.42";
String user = "XXXXXX";
String pass = "XXXXXX";
String filePath = "783771-1.jpg";
String uploadPath = imagePath;
ftpUrl =ftpUrl + user +":"+ pass+"#"+host+"/"+filePath+";";
System.out.println("Upload URL: " + ftpUrl);
try {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
OutputStream outputStream = conn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadPath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File uploaded");
return "File uploaded";
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I am getting an error MalFormedURLException i.e. in detail message "unknown protocol:ftp"
Is there any other option to upload an image using JDeveloper.
Any idea regarding this.
Thanks, Siddharth
Your ftpUrl is wrong. Remove http:// in the host variable. Should be ok then
I haven't really tried ftp upload. But I had tried with multipart form upload. As far as I know, MAF doesnt provide Out-Of-Box support for file upload. What I did was essential recreating the HTTP stream for the image upload.
The POC code is attached below. This may be definitely the CRUDEST implementation but I am not sure if there is a better way.
public void doUpload() {
try {
DeviceManager dm = DeviceManagerFactory.getDeviceManager();
String imgData =
dm.getPicture(50, DeviceManager.CAMERA_DESTINATIONTYPE_FILE_URI, DeviceManager.CAMERA_SOURCETYPE_CAMERA,
false, DeviceManager.CAMERA_ENCODINGTYPE_PNG, 0, 0);
imgData = imgData.substring(7, imgData.length());
int start = imgData.lastIndexOf('/');
String fileName = imgData.substring(start+1, imgData.length());
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
String requestMethod = RestServiceAdapter.REQUEST_TYPE_POST;
String requestEndPoint = restServiceAdapter.getConnectionEndPoint("serverBaseUrl");
String requestURI = "/workers/100000018080264";
String request = requestEndPoint + requestURI;
HashMap httpHeadersValue = new HashMap();
httpHeadersValue.put("X-ANTICSRF", "TRUE");
httpHeadersValue.put("Connection", "Keep-Alive");
httpHeadersValue.put("content-type","multipart/form-data; boundary=----------------------------4abf1aa47e18");
// Get the connection
HttpConnection connection = restServiceAdapter.getHttpConnection(requestMethod, request, httpHeadersValue);
OutputStream os = connection.openOutputStream();
byte byteBuffer[] = new byte[50];
int len;
//String temp is appended before the image body
String temp = "------------------------------4abf1aa47e18\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" +fileName+ "\"\r\nContent-Type: image/jpeg\r\n\r\n";
InputStream stream = new ByteArrayInputStream(temp.getBytes("UTF-8"));
if (stream != null) {
while ((len = stream.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream.close();
}
FileInputStream in = new FileInputStream(imgData);
if (in != null) {
while ((len = in.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
in.close();
}
//The below String is appended after the image body
InputStream stream2 =new ByteArrayInputStream("\r\n------------------------------4abf1aa47e18--\r\n".getBytes("UTF-8"));
if (stream2 != null) {
while ((len = stream2.read(byteBuffer)) >= 0) {
os.write(byteBuffer, 0, len);
}
stream2.close();
}
int status = connection.getResponseCode();
InputStream inputStream = restServiceAdapter.getInputStream(connection);
ByteArrayOutputStream incomingBytes = new ByteArrayOutputStream() // get and process the response.
while ((len = inputStream.read(byteBuffer)) >= 0) {
incomingBytes.write(byteBuffer, 0, len);
}
String ret = incomingBytes.toString();
incomingBytes.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Following is the snippet from a servlet that attempts to fetch image from the URL. I have fetched the bytes. Now how do I display the image on the webpage ?
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
byte res[] = bos.toByteArray();
} finally {
out.close();
}
You Can Rewrite your code like this...see if this helps
public void doGet(HttpRequest request,HttpResponse response)throws ServletException{
response.setContentType("image/jpeg;charset=UTF-8");
response.addHeader("content-disposition", "inline;filename=Default.jpeg");
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new OutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
}
catch(Exception e){
e.printStackTarce();
}
finally {
out.close();
}
}
I want to download multiple files in single zip file using java servlet. I successfully downloaded the zip file containing multiple files (in my web page). but the problem is that files are also downloaded in my server(for ex in my jboss bin folder).
Code:
public void createZipFile(String fileNames,HttpServletResponse response,HttpServletRequest request) {
try {
ZipOutputStream outStream1 = null;
ServletOutputStream outStream=null;
FileInputStream inStream =null;
FileOutputStream fos=null;
InputStream inputStream =null;
int bytesRead = 0;
String zipFileName = "zipFileName.zip";
response.setHeader("Content-Disposition", "attachment;filename=\""+zipFileName+"\"");
response.setHeader("Pragma", "private");
response.addHeader("Cache-Control", "no-transform, max-age=0");
response.setHeader("Accept-Ranges", "bytes");
response.setContentType("application/zip");
//fileNames contains multiple file name.so i want to split and get each file
String[] fileName = fileNames.split(",");
byte[] buffer = new byte[1024];
outStream1 = new ZipOutputStream(new FileOutputStream(zipFileName));
for(int i = 0; i < fileName.length; i++) {
String filePath=audioFile.getAllFiles(fileName[i], Integer.parseInt(userId));
inputStream = new URL("************************server File location***************************").openStream();
String fileNaming = fileName[i];
String[] tempFile = fileNaming.split("\\.");
String tempFileExt=tempFile[1];
String temporaryFile=tempFile[0]+"."+tempFileExt;
fos = new FileOutputStream(temporaryFile);//here is the problem(temporary file created in my server -bin folder.but i dont want this to create)
int length = -1;
while ((length = inputStream.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
inStream = new FileInputStream(fileName[i]);
outStream1.putNextEntry(new ZipEntry(fileName[i]));
fos.close();
inputStream.close();
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream1.write(buffer, 0, bytesRead);
}
}
inStream.close();
outStream1.closeEntry();
outStream1.close();
int bytesRead1 = 0;
byte[] buff = new byte[1024];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
FileInputStream inStream1 =new FileInputStream(zipFileName);
while ((bytesRead1 = inStream1.read(buff)) != -1)
{
bao.write(buff, 0, bytesRead1);
}
byte[] videoBytes = bao.toByteArray();
response.setContentLength(videoBytes.length);
outStream = response.getOutputStream();
outStream.write(videoBytes);
outStream.flush();
outStream.close();
bao.close();
response.flushBuffer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
For whatever reason, you're copying the files twice. Once, to the file system via inputStream and fos, and the second time to the ZipFile, via inStream and outStream1.
Seems like you can simply remove all of the code related to inputStream and fos, and you won't create the files on your filesystem.
What I am trying to do is to zip a generated csv file. The file does get generated without issue until it comes to this code here. So the code throws the exception at zos.close() here's the code
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null) zos.putNextEntry(ze);
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
byte[] buffer = new byte[1024];
int len;// = in.read(buffer);
while ((len = in.read(buffer)) > 0) {
Logger.debug("in Loop, len = " + len);
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
} catch(IOException ex) {
Logger.error(ex);
}
Corrected Code
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
FileOutputStream fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null){
zos.putNextEntry(ze);
}
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}
You create fos and zos once at the top of your code:
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
then add a ZipEntry:
if(ze != null) zos.putNextEntry(ze);
then redifine them later:
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
then close the new zos. You never closed, nor wrote to the first zos (which had a ZipEntry) and never added a ZipEntry to the second (which you tried to close without any). Hence, the At Least One ZipEntry error.
------------ Edit --------------
Try adding zos.finish(), also, your close() methods should be in a finally block...
ZipOutputStream zos = null;
FileInputStream in = null;
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName));
in = new FileInputStream(file.getPath());
zos.putNextEntry( new ZipEntry(fullZipFileName) );
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.finish();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}finally {
if ( zos != null ) {
try {
zos.close();
} catch ( Exception e ) {}
}
if ( in != null ) {
try {
in.close();
} catch ( Exception e ) {}
}
}