How to download data from url? - download

I can download data via HttpUrlConnection and InputStream but I need to download raw-data. So, i want to create a DownloadManager via raw-data, then using raw-data I convert this data to binary or image format. According to my research, I see "download file from url" but I can't download file in mac? Always, I get FileNotFoundException. Please help me. How I can download data from url?
public class DownloadData extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
downloadData("https://blablalabla/get");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void downloadData(String myurl) throws IOException {
URL u = new URL(myurl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
OutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/Users/ilknurpc/Desktop/text.docx"));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length);
}
}
}

If you want to construct a workable download manager, I would suggest that you take a look at the
Tomcat Default Servlet Implementation
.
There a few number of HTTP headers that you need to understand such as E-Tags and Http Range Headers for a proper implementation.
Thankfully the Tomcat Default Servlet handles the prerequisites for you.
You can adapt this servlet in your code with minor changes (package declaration etc).

Related

To make a download functionality to download files from the server using spring boot

I want to make a download functionality which has to download a file from the server using spring boot.
The size limit of the file should be 1gb and I should have an option to download it as a zip file
Hello to download any type of file you can use the following method. You must have configured the path before applying it.
//descargar archivo
#Secured({ "ROLE_ADMIN", "ROLE_USER","ROLE_SADMIN","ROLE_USERGESTSERV"})
#RequestMapping(value="/downloadFile/{filename:.+}")
public void getLogFile(HttpSession session,HttpServletResponse response,#PathVariable String filename) throws Exception {
try {
final Logger log = LoggerFactory.getLogger(getClass());
Path pathFoto = getPath(filename);
log.info("pathFoto: " + pathFoto);
Resource recurso = new UrlResource(pathFoto.toUri());
File fileToDownload = new File(pathFoto.toString());
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;recurso");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception exception){
System.out.println(exception.getMessage());
}
}

display image from file system in jsp using spring boot

I have Java Web Application using Spring Boot, I want to display in JSP page ,images which are in an extern folder (E:/images) in file system.
I looked too many pages in google,I found on stackoverflow a post that say I should write a servlet to get the image : am I missing something or should I do it with an other way , please give me more details I m kind of new to Spring. thanks for your help.
in my Controller :
#RequestMapping(value="/images",method = RequestMethod.GET)
public #ResponseBody void affichimage(#RequestParam("id") Integer Iddd,HttpServletResponse response,HttpServletRequest request) throws IOException
{
Annonce annonce=new Annonce();
annonce=annoncedao.findOne(Iddd); // get the right annonce from
//database
File imageFile = new File(annonce.getimage()); // in image I have
//the link to images ex : E:/images/image1.jpeg
response.setContentType("image/jpeg");
BufferedImage image = ImageIO.read(imageFile);
ImageIO.write(image, "image/jpeg", response.getOutputStream());
}
in JSP :
< img class="imagesaffichage" src="/images?id=${annonce.id}" alt="No image"/>
I also added this to my application :
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("file:///E:/images/");
}
I found the solution , I had to change the above method :
#RequestMapping(value="/images",method = RequestMethod.GET)
public #ResponseBody void affichimage(#RequestParam("id") Integer
Iddd,HttpServletResponse response,HttpServletRequest request) throws
IOException,NullPointerException
{
Annonce annonce=new Annonce();
annonce=annoncedao.findOne(Iddd); // get the right annonce from
//database
File imageFile = new File(img);
response.setContentType("image/jpeg");
InputStream in=new FileInputStream(imageFile);
IOUtils.copy(in, response.getOutputStream());
}

Generated PDF not send in the browser

I build a PDF document with iText library, and i want to get this document by clicking a link in the webapp.
But, it happens... nothing. No error message, no exception, really nothing.
I really don't master IO Streaming, so I think I made a mistake on this point, but after few hours of research, I don't know and I need a bit of help.
I have two methods. The first is the one to create pdf doc.
public void exporterPDF(SomeObjectIWillUse o) {
Document documentPDF = new Document(PageSize.A4);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(documentPDF, baos);
documentPDF.open();
documentPDF.addTitle("Test ! ");
Paragraph par = new Paragraph("Liste des participants");
documentPDF.add(par)
documentPDF.close();
telechargerPdfViaVue(FacesContext.getCurrentInstance(), baos, "filename.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
JsfUtils.addMessageByCode(FacesMessage.SEVERITY_FATAL, "drc.export.generation.pdf.erreur");
}
}
And the second is use to send the document.
public static final void telechargerPdfViaVue(FacesContext context, ByteArrayOutputStream baos, String fileName) throws IOException, DocumentException {
ExternalContext externalContext = context.getExternalContext();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName);
externalContext.setResponseContentLength(baos.size());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
context.responseComplete();
}
and it's called on my web page by a simple commandeLink
<p:commandLink id="exportPdf" action="#{myBean.exporterPDF(o)}">
Literally, in debug mode, all is done, but nothing happen...
Thank you for your help!
More informations, I use :
- JSF 2.2.7
- Spring 4.0.6

Spring boot 1.3.x MultipartFile.transferTo null after migration from 1.2.x

I am facing error MultipartFile error for one day after having upgrade from Spring Boot 1.2.7 to 1.3.1.
What I notice is that the default is now Jetty 9.2 and no more Tomcat 8. Everything was fine until I tried to write an uploaded file using MultipartFile.transferTo(File file) method..
MultipartFile.transferTo() method is calling an implementation of javax.servlet.http.Part Which is implemented this way for tomcat 8
#Override
public void write(String fileName) throws IOException {
File file = new File(fileName);
if (!file.isAbsolute()) {
file = new File(location, fileName);
}
try {
fileItem.write(file);
} catch (Exception e) {
throw new IOException(e);
}
}
and this way for jetty 9.2
public void write(String fileName) throws IOException
{
if (_file == null)
{
_temporary = false;
//part data is only in the ByteArrayOutputStream and never been written to disk
_file = new File (_tmpDir, fileName);
BufferedOutputStream bos = null;
try
{
bos = new BufferedOutputStream(new FileOutputStream(_file));
_bout.writeTo(bos);
bos.flush();
}
finally
{
if (bos != null)
bos.close();
_bout = null;
}
}
else
{
//the part data is already written to a temporary file, just rename it
_temporary = false;
File f = new File(_tmpDir, fileName);
if (_file.renameTo(f))
_file = f;
}
}
What's wrong with the Jetty implementation is that is waiting for file name File.getName() and not the absolute path name File.getPath() which is provided by the call of StandardMultipartHttpServletRequest.transferTo(File file)
#Override
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
Is this a bug ? Note that this occurs since I have upgraded from spring boot 1.2.7 to 1.3.1. The default was Tomcat and now it is Jetty...
Per the javadoc for javax.servlet.http.Part.write(String filename) the filename parameter is ...
The file is created relative to the location as specified in the
MultipartConfig
In the code you referenced in Jetty 9.2, namely this ...
jetty-9.2.14.v20151106 - MultiPartInputStreamParser.write(String fileName)
You'll see that there's 2 possible code paths it takes, the first is the "in memory" path, and the second is "file on disk" approach.
In both cases, when you specify a filename to Part.write(String) that name is relative to your MultiPartConfig.location (a configuration of which you haven't detailed in your question).
The implementation of MultiPartInputStreamParser has a _tmpDir which is configured from the webapp's MultiPartConfig.location.
If you want this to behave properly, would highly recommend you define a MultiPartConfig.location that is appropriate for your application, instead of relying on the container to pick one.
The Tomcat approach of allowing absolute filenames in Part.write(String) is actually not allowed in the servlet spec (mainly as its a security issue that can be used to cause havoc on a system)
Ok, at the moment if you want to get rid of this error you can switch back to Tomcat instead of Jetty.
Put tomcat into your dependencies:
compile('org.springframework.boot:spring-boot-starter-tomcat')
And declare tomcat as container:
#Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
return new TomcatEmbeddedServletContainerFactory();
}

ResponseBody cannot be resolved to a type

I'm trying to write this method in my controller:
#ResponseBody
#RequestMapping(value = {"/getTeams"}, method = RequestMethod.GET)
public void getMaxRequestSize(HttpServletResponse response) {
String autoCompleteList = null;
List<Team> teams = atService.getAllTeams();
Iterator itr = teams.iterator();
while (itr.hasNext()) {
autoCompleteList += itr.next().toString() + "\n";
}
response.setContentType("text/html");
PrintWriter writer;
try {
writer = response.getWriter();
writer.write(autoCompleteList);
} catch (IOException e) {
e.printStackTrace();
}
}
For some reason I always get an error on the ResponseBody annotation (= cannot be resolved to a type). I googled for quite a while and didn't find a solution. I'm sure it's something silly. I can use all the other annotations without any problems...
Is this a Maven project? You might be ending up with the old Spring 2.5.6 jars in your war file instead of Spring 3. Eclipse's POM editor's Dependency Hierarchy tab can help you figure out if that's the case.

Resources