私はダウンロードServletを書いて、messageIDパラメータに基づいてファイルを返しました。以下はdoGetメソッドです。HTTPでファイルをダウンロードする
@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();
}
次に、ファイルを取得するコードを書きました。
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();
}
このコードは正常に動作します。私はオーディオファイルをダウンロードすることができ、それは正しく動作します。私が知りたいのは、ファイル名を自分の名前にするのではなく、ファイルの名前を取得する方法です。また、ストリームから読み込むことなくファイルを取得することは可能ですか(おそらくあなたのためにそれを行うライブラリ)?私は汚いものを隠したいと思っています。
おかげで添付ファイル付きの
Content-dispositionエントリで任意のファイル名を指定できます。 – adatapost
ストリームの使用を助けるためにIOUtilsのcommons-ioを見てください。 – Steven
クライアントアプリケーションから後でそれを取得するにはどうすればよいですか?私はヘッダーを解析する必要がありますか? –