I wrote a boot servlet to return a file based on the messageID parameter. The following is the doGet method.
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // This messageID would be used to get the correct file eventually long messageID = Long.parseLong(request.getParameter("messageID")); String fileName = "C:\\Users\\Soto\\Desktop\\new_audio1.amr"; File returnFile = new File(fileName); ServletOutputStream out = response.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType("C:\\Users\\Soto\\Desktop\\new_audio1.amr"); response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); response.setContentLength((int)returnFile.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + "new_audio.amr" + "\""); FileInputStream in = new FileInputStream(returnFile); byte[] buffer = new byte[4096]; int length; while((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.flush(); }
Then I wrote code to extract the file.
String url = "http://localhost:8080/AudioFileUpload/DownloadServlet"; String charset = "UTF-8"; // The id of the audio message requested String messageID = "1"; //URLConnection connection = null; try { String query = String.format("messageID=%s", URLEncoder.encode(messageID, charset)); //URLConnection connection; //URL u = new URL(url + "?" + query); //connection = u.openConnection(); //InputStream in = connection.getInputStream(); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpGet httpGet = new HttpGet(url + "?" + query); HttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine()); InputStream in = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Soto\\Desktop\\new_audio2.amr")); byte[] buffer = new byte[4096]; int length; while((length = in.read(buffer)) > 0) { fos.write(buffer, 0, length); } //connection = new URL(url + "?" + query).openConnection(); //connection.setRequestProperty("Accept-Charset", charset); //InputStream response = connection.getInputStream(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Now this code is working fine. I can upload an audio file and it works correctly. I want to know how, if possible, to get the file name as it is downloaded, instead of giving it my name. Also, is it possible to get a file without reading from a stream (maybe some kind of library that does this for you)? I kind of want to hide dirty things.
thanks
source share