Ответ 1
Вы можете добавить Content-Disposition
header в ответ, например.
rb.header("Content-Disposition", "attachment; filename=\"thename.jpg\"");
В настоящее время у меня есть метод в Джерси, который извлекает файл из репозитория контента и возвращает его как ответ. Файл может быть jpeg, gif, pdf, docx, html и т.д. (В основном что угодно). В настоящее время, однако, я не могу понять, как я могу контролировать имя файла, так как каждый файл автоматически загружается с именем (загрузка. [Расширение файла] ie (download.jpg, download.docx, download.pdf). Есть ли способ, которым я может установить имя файла? У меня уже есть это в String, но я не знаю, как установить ответ так, чтобы он отображал это имя файла, а не по умолчанию для "загрузки".
@GET
@Path("/download/{id}")
public Response downloadContent(@PathParam("id") String id)
{
String serverUrl = "http://localhost:8080/alfresco/service/cmis";
String username = "admin";
String password = "admin";
Session session = getSession(serverUrl, username, password);
Document doc = (Document)session.getObject(session.createObjectId(id));
String filename = doc.getName();
ResponseBuilder rb = new ResponseBuilderImpl();
rb.type(doc.getContentStreamMimeType());
rb.entity(doc.getContentStream().getStream());
return rb.build();
}
Вы можете добавить Content-Disposition
header в ответ, например.
rb.header("Content-Disposition", "attachment; filename=\"thename.jpg\"");
Еще лучший способ, который более типичен, используя Джерси, предоставил класс ContentDisposition
:
ContentDisposition contentDisposition = ContentDisposition.type("attachment")
.fileName("filename.csv").creationDate(new Date()).build();
return Response.ok(
new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
outputStream.write(stringWriter.toString().getBytes(Charset.forName("UTF-8")));
}
}).header("Content-Disposition",contentDisposition).build();
В том случае, если вы не используете класс ResponseBuilder, вы можете установить заголовок непосредственно на ответ, который избегает любых дополнительных зависимостей:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"somefile.jpg\"").build();
@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
File f = new File("/home/mpasala/Documents/Example.zip");
String filename= f.getName();
if (!f.exists()) {
throw new WebApplicationException(404);
} else {
Boolean success = moveFile();
}
return Response
.ok(f)
.header("Content-Disposition",
"attachment; filename="+filename).build();
}
Здесь я нахожу решение своей проблемы. Я добавил имя файла в заголовок ответа.