I have given a URI which is from google drive direct download link of a image, and I want to find the file extension of the file that is returned, what do I have to do in Java.
For example Link will be like:https://drive.google.com/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
`
public static String saveImage(String imageUrl, String playlist) throws
IOException {
URL url = new URL(imageUrl);
String fileName = url.getFile();
System.out.println(fileName);
String destName
="./figures"+fileName.substring(fileName.lastIndexOf("/"));
String destName = "../imgUpload/"+playlist;System.out.println(destName);
InputStream is = url.openStream();System.out.println("is-
1"+is);OutputStream os = new FileOutputStream(destName);
System.out.println("is"+is);
byte[] b = new byte[2048];int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
return destName;
}
`
O/P:-
fileName--/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
fileName-extrect from link-/uc?export=download&id=0BwtDpsO0CtJZbm9iNUNMTXNTX0k
For your example URL there is a redirect to a different URL, but a request to that URL returns a response with the header content-type. For your example it is image/jpeg.
Related
I'm trying to open a pdf file in which has been exported from a repository. Here is the code that I'm using:
ConnectionManager con = new ConnectionManager();
String id = request.getParameter("uname");
String objname = request.getParameter("pass");
Properties prop = new Properties();
//ResourceBundle resource = ResourceBundle.getBundle("query");
//prop.load(getClass().getResourceAsStream("query.properties"));
String uname = "DmAdmin";
String pass = "<pass>";
String docbase = "QDocs";
String ext = new String();
IDfSession ssn = con.getSession(uname, pass, docbase);
sysObj = (IDfSysObject)ssn.getObject((IDfId)new DfId(id));
//ByteArrayInputStream buf = sysObj.getContent();
//sysObj.getFile("C:\\Users\\rsaha04\\Downloads\\"+objname+".pdf");
String path = "C:\\Users\\rsaha04\\Downloads\\";
String filename = path + sysObj.getObjectName().toString();
IDfCollection coll = sysObj.getRenditions(null);
if (coll != null)
{
while (coll.next())
{
String format = coll.getString("full_format");
{
if (format.equalsIgnoreCase("pdf"))
{
ext = "pdf";
System.out.println("extension set: "+ext);
}
}
}
filename = filename+"."+ext;
sysObj.getFileEx(filename, ext, 0, false);
}
con.closeConnection(ssn);
//Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+filename);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename='"+filename+"'");
I'm able to open the pdf file in adobe acrobat reader but it is failing for browser with this error.
Please help me understand where I'm going wrong here.
You need your server to respond with a pdf file. You set the response headers, but your code never writes the pdf data into the response.
Do that using
response.write(bytesFromPdfFile)
I am going to upload either CSV file or PDF file to Google Cloud Storage using this code:
public static String uploadFile(String fileName, String fileLocation, final String bucketName) throws IOException {
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
fileName += dtString;
// The InputStream is closed by default, so we don't need to close it here
// Read InputStream into a ByteArrayOutputStream.
File file = new File(fileLocation);
InputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] readBuf = new byte[4096];
while (is.available() > 0) {
int bytesRead = is.read(readBuf);
os.write(readBuf, 0, bytesRead);
}
is.close();
// Convert ByteArrayOutputStream into byte[]
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, fileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
os.toByteArray());
// return the public download link
return blobInfo.getMediaLink();
}
When I download the uploaded file, if it is a CSV file, it is fine, but when I download the PDF file, it always show a blank page. And it is also shown a blank page on the console itself.
Do not use available() as it just provides a means to prevent blocking, trying to read more than the OS file buffer already has read. It can be 0 at any time,
pending following physical reads.
while (true) {
int bytesRead = is.read(readBuf);
if (bytesRead < 0) {
break;
}
os.write(readBuf, 0, bytesRead);
}
Or simply use:
Path file = Paths.get(fileLocation);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Files.copy(file, os);
I have one spring controller, I want to download file in specific path like D:// or K://, But right now it will be download in downloads folder by default.
I am taking my file from /WEB-INF/ folder (server side located in Tomcat folder) and i want to write in client machine D:\ drive please see my below code is something wrong please let me know. I am using google crome.
Thanks in Advance
public void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//ServletContext context = request.getServletContext();
String filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/"+"out.json";
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
//String fullPath = appPath + filePath;
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
System.out.println("downloadFile.getName()" + downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
You cannot decide where the client will save the downloaded file on server side - in fact, you cannot even affect whether it will save it anywhere at all! That's for the client (e.g. Chrome) to decide.
See Chrome help for how to change default download location in Chrome.
Hello friends,
I have the following code to upload a image to my WebApp in folder WebContent-->images-->menuitemimg
private String doUploadFile(String menuItemName,Long menuItemId){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
InputStream inputStream = null;
OutputStream out = null;
String imageName = null;
try{
String dirPath = externalContext.getRealPath(File.separator+"images"+File.separator+"menuitemimg");
File targetFolder = new File(dirPath);
targetFolder.mkdirs();
imageName = file.getFileName();
imageName = menuItemName+"_"+menuItemId+"."+FilenameUtils.getExtension(imageName);
inputStream = file.getInputstream();
out = new FileOutputStream(new File(targetFolder+File.separator+imageName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
return imageName;
}
The code is just working fine. But when I restart server the images uploaded in menuitemimg folder get vanished. I don't want to store images on disc or in database. So what I suppose to do.
Thanks in advance.
I went through you code, it seems you are storing images inside you project folder itself.
I would suggest you to upload your images somewhere else outside the container.
I have JBoss running as application server and somewhere on my HD there is a PDF file, that gets created when the user clicks on a specific action. Let's say the file is here: C:/PDF/doonot/10.07.2012/doonot.pdf. How can I offer this file as download? I already did it for a CSV file, but I don't know how to do it with PDF.
Any help is much appreciated.
as i wrote on Is there a common way to download all types of files in jsp?
you can use something like this:
public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){
HttpServletResponse response = httpServletResponse;
InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/
String filename = "";
String agent = request.getHeader("USER-AGENT");
if (agent != null && agent.indexOf("MSIE") != -1)
{
filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename=" + filename);
}
else if ( agent != null && agent.indexOf("Mozilla") != -1)
{
response.setCharacterEncoding("UTF-8");
filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
}
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
out.write(by, 0, index);
index = in.read(by, 0, 32768);
}
out.flush();
return response;
}
UPDATE:
Dont forget that you can use the InputStream as this:
// read local file into InputStream
InputStream inputStream = new FileInputStream("c:\\SOMEFILE.xml");
or you can use it even like this
//read from database
Blob blob = rs.getBlob(1);
InputStream in = blob.getBinaryStream();
You can simply write a servlet wich read the pdf and write it to the response output stream.
Exemple here : http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html
Yes Gustav is right. Java doesn't discriminate amongst file types. A file is a file, if you did it for csv, it should also work for pdf.