首页 > 编程知识 正文

springboot获取类路径,springboot实现文件上传

时间:2023-05-06 02:56:29 阅读:130159 作者:2823

springboot项目基于文件路径实现文件下载功能非常简单! 我们上传文件的时候,经常会上传到文件服务器上! 此时,让前端下载。 前端可能无法基于文件路径下载。 这个时候还是需要我们的后端参选! 在这种情况下,前端只需将文件路径传递给后端,后端就可以通过在Http请求中请求文件,然后在获得Http返回主体时将其转换为输入流格式来实现下载功能。 1 .导入jar包或maven相关性

ependencygroupidcn.Hu tool/groupidartifactidhutool-all/artifactidversion5.4.2/version/dependency2.指南包

import cn.Hu tool.http.http request; import cn.Hu tool.http.httpresponse; import cn.hutool.http.HttpUtil; import javax.servlet.http.http无servlet保罗; import java.io.*; import java.net.URLEncoder; 3 .控制器层代码:

/** *下载通用文件* * @param filePath文件的完整路径(复制文件的路径可在浏览器中访问) @ param response * @ throws exception (/@ request down lling public void download (@ request param ) value='filepath ',required=false )字符串文件路径, httpservletresponseresponse (throws exception (/路径为空,无法保存if (string utils.isempty ) filepath ) ) { thrownewglobalexception (siteresourcesenum.missing _ parameters.getmsg ),siteresourcesenum.missing _ parameters } httpresponse execute=get.execute (; //获取导入文件的输入流对象(bufferedinputstreambis=newbufferedinputstream ) execute.bodystream ); //文件后缀string filename=file path.substring (file path.lastindexof ('/' ) ); response.set content type (应用程序/octet-stream ); //设置响应标头,attachment表示作为附件下载,inline表示response.setheader (content-disposition )、) attachment; filename=' urlencoder.encode (filename,' UTF-8 ' ); //输出流对象(用于写入文件) bufferedoutputstreambos=newbufferedoutputstream (response.get output stream ) ); //下载文件并使用spring框架的FileCopyUtils工具(在内部自动关闭流并释放资源) filecopyutils.copy(bis,bos ); system.out.println ('======================文件下载成功

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