サーバーからユーザーのコンピューターにzipアーカイブを保存したい。このファイルに関するいくつかの情報を表示し、ダウンロードボタンがあるWebページがあります。私のコントローラーのボタンのアクションでは、ホームページにリダイレクトするだけですが、データベースからデータを取得して、パスがユーザーによって定義されているユーザーのマシンに保存したい
問題は、どうすればこのパスを取得できるかわからないことです。どうすればそれができるか、例を挙げていただけますか?
コントローラメソッドでは、このコードを追加してファイルをダウンロードできます
File file = new File("fileName");
FileInputStream in = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
in.read(content);
ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());
パスはユーザーによって定義されるため、パスの取得方法を知る必要はありません:)ただし、ダウンロードパスを探している場合は、Webサイトのソースコードとダウンロードボタンのリンク先を確認してください。通常、の先頭に表示されます<form>
。
ファイルのダウンロードを探しているだけの場合:
public void download(String filename, String url) {
URL u;
InputStream is = null;
DataInputStream dis;
String s;
try{
u = new URL(url);
// throws an IOException
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
FileWriter fstream = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(fstream);
while ((s = dis.readLine()) != null) {
// Create file
out.write(s);
//Close the output stream
out.close();
}
}catch (Exception e){ //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
is.close();
}
お役に立てれば...
外部URLまたはS3からダウンロードする場合:::
@RequestMapping(value = "asset/{assetId}", method = RequestMethod.GET)
public final ResponseEntity<Map<String, String>> fetch(@PathVariable("id") final String id)
throws IOException {
String url = "<AWS-S3-URL>";
HttpHeaders headers = new HttpHeaders();
headers.set("Location", url);
Map<String, String> map = null;
ResponseEntity<Map<String, String>> rs =
new ResponseEntity<Map<String, String>>(map, headers, HttpStatus.MOVED_PERMANENTLY);
return rs;
}