我正在尝试开发REST服务,并设法返回我需要的所有数据。但是我想创建一个临时的文件并在其中添加一些文件,并将所有这些对象(带有文件的文件夹)放在zip文件中,当调用REST服务时,将下载zip文件。 这是代码:
public class rest {
private static final String FILE_PATH = "file.xml";
@GET
@Path( "/GetSequenceId/{id}" )
@Consumes( MediaType.APPLICATION_XML )
@Produces( MediaType.TEXT_XML )
// @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response showFileStoreDetails( @PathParam( "id" ) String id)
throws ArchiveException, IOException {
Response response = null;
File file = new File( FILE_PATH );
// String feeds = null;
Sequence feedData = null;
Step step = new Step();
Liststeps listStep = new Liststeps();
Attachement attachement = new Attachement();
List<String> listOfAttachement = new ArrayList<String>();
// List<attachement> listAttachementd = null;
// File file = new File( "file.xml" );
// Response response = null;
// System.out.println( listOfAttachement );
try {
/*
* Database database = new Database(); Connection connection =
* database.Get_Connection();
*/
feedData = listStep.getSteps( Integer.parseInt( id ) );
listOfAttachement = listStep.getAttachementId();
System.out.println( listOfAttachement );
System.out.println( "------------Debut---------------------------------------" );
for ( String att : listOfAttachement ) {
MongoClient mongoClient = new MongoClient( "localhost", 27017 );
DB mongoDB = mongoClient.getDB( "tutorial" );
// Let's store the standard data in regular collection
DBCollection collection = mongoDB.getCollection( "filestore" );
/// logger.info( "Inside downloadFilebyID..." );
// logger.info( "ID: " + id );
BasicDBObject query = new BasicDBObject();
query.put( "_id", att );
// System.out.println( "Mongo_ID :" +
// att.getIdMongo().toString() );
DBObject doc = collection.findOne( query );
DBCursor cursor = collection.find( query );
if ( cursor.hasNext() ) {
Set<String> allKeys = doc.keySet();
HashMap<String, String> fields = new HashMap<String, String>();
for ( String key : allKeys ) {
fields.put( key, doc.get( key ).toString() );
}
/*
* logger.info( "description: " + fields.get( "description"
* ) ); logger.info( "department: " + fields.get(
* "department" ) ); logger.info( "file_year: " +
* fields.get( "file_year" ) );
*/
// logger.info( "filename: " + fields.get( "filename" ) );
GridFS fileStore = new GridFS( mongoDB, "filestore" );
GridFSDBFile gridFile = fileStore.findOne( query );
InputStream in = gridFile.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data = in.read();
while ( data >= 0 ) {
out.write( (char) data );
data = in.read();
}
out.flush();
ResponseBuilder builder = Response.ok( out.toByteArray() );
builder.header( "Content-Disposition", "attachment; filename=" + fields.get( "filename" ) );
response = builder.build();
}
}
// ProjectManager projectManager = new ProjectManager();
// feedData = listStep.getSteps( Integer.parseInt( id ) );
System.out.println( "--------------fin-----------------------------------" );
// listAttachementd = listStep.getAttachement();
// StringBuffer sb = new StringBuffer();
// Gson gson = new Gson();
// System.out.println( gson.toJson( feedData ) );
// feeds = gson.toJson( feedData );
// String xml = org.json.XML.toString(gson);
// XStream xstream = new XStream();
// File file = new File( "input.xml" );
// try {
//
// // File file = new File( "input.xml" );
// JAXBContext jaxbContext = JAXBContext.newInstance( Sequence.class
// );
// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//
// // output pretty printed
// jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT,
// true );
//
// jaxbMarshaller.marshal( feedData, file );
// jaxbMarshaller.marshal( feedData, System.out );
//
// } catch ( JAXBException e ) {
// e.printStackTrace();
// }
} catch ( NumberFormatException e ) {
System.out.println( e );
} catch ( Exception e ) {
e.printStackTrace();
}
/*
* ResponseBuilder response = Response.ok( (Object) file );
* response.header( "Content-Disposition",
* "attachment; filename=\"sequence.xml\"" ); System.out.println( file
* );
*
* return response.build();
*/
return response;
}
}
答案 0 :(得分:0)
为此,您可以直接创建文件夹,添加文件并将其压缩到文件系统上。然后你可以使用HttpServletResponse OutputStream。通过这种方式,您可以完成所有文件处理,您可以在HttpServletResponse OutputStream中简单地加载zip文件,最后从文件系统中删除所有处理文件,并为用户提供下载流
示例:
`@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
@Context HttpServletResponse response) throws IOException {
try {
//Get your File or Object from wherever you want...
//you can use the key parameter to indentify your file
//otherwise it can be removed
//let's say your file is called "object"
response.setContentLength((int) object.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ object.getName());
ServletOutputStream outStream = response.getOutputStream();
byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
DataInputStream in = new DataInputStream(
object.getDataInputStream());
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
outStream.write(bbuf, 0, length);
}
in.close();
outStream.flush();
} catch (S3ServiceException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
return Response.ok().build();
}
`
答案 1 :(得分:0)
您可以创建临时文件夹
Files.createTempDirectory(prefix, FileAttribute[] attrs);
然后用ZipOutputStream创建zip文件