首页 > 编程知识 正文

java文件下载如何实现,springmvc实现文件下载

时间:2023-05-06 00:08:15 阅读:50533 作者:2764

需要从网站下载PDF。 PDF必须用代码生成。 我认为这将是freemarker和iText等PDF生成框架的组合。 有更好的方法吗?

但是,我的主要问题是如何允许用户从Spring Controller下载文件?

#1楼

通过使用Spring的ResourceHttpMessageConverter中内置的支持,可以简化此过程。 如果可以确定mime类型,则将设置内容长度和内容类型

@ request mapping (value='/files/{ file _ name } ',method=RequestMethod.GET ) )。

@响应主体

publicfilesystemresourcegetfile (@ path variable ) ) file_name ) String fileName ) {

returnnewfilesystemresource (my service.getfile for ) filename );

}

#2楼

在Spring 3.0中,可以使用HttpEntity返回对象。 此选项使测试更容易,因为控制器不需要http servlet的response对象。 除此之外,这个答案是对Infeligo之一。

如果pdf框架的返回值是字节数组(有关其他返回值,请参见我的回答的第二部分)。

@ request mapping (value='/files/{ filename } ',method=RequestMethod.GET ) )。

公共http实体创建pdf (

@pathvariable(filename ) ) String fileName ) throws IOException {

byte [ ]文档主体=this.pdf framework.create pdf (文件名称;

httpheadersheader=newhttpheaders (;

header.set content type (介质类型. application _ pdf;

header.set (http headers.content _ disposition,

'附件; filename=' fileName.replace (',' _ ' );

header.set contentlength (文档主体. length );

returnnewhttpentity (文档主体,头部);

}

如果pdf框架的“返回类型”(documentBbody )还没有字节数组,也没有字节输入,则最好不要首先将其设置为字节数组。 相反,建议按以下方式使用

文件系统资源示例:

@ request mapping (value='/files/{ filename } ',method=RequestMethod.GET ) )。

公共http实体创建pdf (

@pathvariable(filename ) ) String fileName ) throws IOException {

文件文档=this.pdf framework.create pdf (filename;

httpheadersheader=newhttpheaders (;

header.set content type (介质类型. application _ pdf;

header.set (http headers.content _ disposition,

'附件; filename=' fileName.replace (',' _ ' );

header.set contentlength (文档. length ) );

returnnewhttpentity (newfilesystemresource )文档),

头儿;

}

#3楼

单击jsp链接后,此代码可以从spring控制器自动下载文件。

@ request mapping (value='/download log file ' ) )。

publicvoidgetlogfile (http会话,http servlet响应) throws Exception { )。

try {

stringfilepathtobeserved=//completefilenamewithpath;

filefiletodownload=新文件(filepathtobeserved;

inputstream inputstream=new文件inputstream (filetodownload );

response.set content type (应用程序/力下载);

response.setheader (' content-disposition ',' attachment; filename=' fileName '.txt ';

Ioutils.copy(Inputstream,response.getOutputStream ();

response.flushBuffer (;

inputStream.close (;

}catch(exceptione ) {

logger.debug (requestcouldnotbecompletedatthismoment.please try again.' );

e .打印堆栈跟踪(;

}

}

#4楼

如果你:

在发送到响应之前,将整个文件发送到byte[];

需要在InputStream上发送/下载

希望完全控制要发送的Mime类型和文件名;

请其他@ControllerAdvice捡起异常。

需要以下代码:

@ request mapping (value='/stuff/{ stuff id } ',method=RequestMethod.GET )。

publicresponseentitydownloadstuff (@ pathvariableintstuffid ) )。

throws IOException {

string full path=stuff service.figureoutfilenamefor (stuff id;

file file=new file (完整路径;

httpheadersrespheaders=newhttpheaders (;

resp headers.set content type (应用程序/pdf );

resp headers.set contentlength (12345678;

resp headers.setcontentdispositionformdata (' attachment ',' fileNameIwant.pdf ' );

inputstreamresourceisr=newinputstreamresource (新文件inputstream (file ) );

returnnewresponseentity(ISR,respHeaders,HttpStatus.OK );

}

另外,请注意读取整个文件不仅仅是为了计算长度。 建议预先保存。 已检查InputStreamResource文档。

#5楼

下面的代码为我工作以生成和下载文本文件。

@请求映射(value='/download ',method=请求方法. get )。

publicresponseentitygetdownloaddata throws exception

string regdata=' loremipsumissimplydummytextoftheprintingandtypesettingindustry.loremipsumhasbeentheindustry ' standardumion whenanunknownprintertookagalleyoftypeandscrambledittomakeatypespecimenbook.ithassurvivednotonlyfivecenturies, butalsotheleapintoelectronictypesetting, remainingessentiallyunchanged.itwaspopularisedinthe 1960 swiththereleaseofletrasetsheetscontainingloremipsumpasssages, andmorerecentlywithdesktoppublishingsoftwarelikealduspagemakerincludingversionsofloremipsum.';

byte[] output=regData.getBytes (;

httpheadersresponseheaders=newhttpheaders (;

responseheaders.set('charset ',' utf-8 ' );

响应标题. set content type (media type.value of (' text/html ' );

响应标题. set contentlength (output.length );

response headers.set (' content-disposition ',' attachment; filename=filename.txt ';

returnnewresponseentity(output,responseHeaders,HttpStatus.OK );

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。