首页 > 编程知识 正文

springboot上传文件超时,springboot文件上传路径

时间:2023-05-06 18:47:43 阅读:132555 作者:3842

前言上传文件的需求也是日常开发中不可缺少的操作,今天我们来总结一下。 一般来说,上传图片的操作,很多稍微大一点的公司都有专用的图片服务器,直接上传图片就可以了。 如果没有图像服务器,这里也将图像汇总成文件进行说明。 本文的代码基于springBoot

上传到哪里? 这个问题在实现需求的时候也一定要考虑吧。 如果确定项目是单个服务器结构,则为了方便,可以采用上传到本地服务器的项目,但在分布式环境中,如果某些文件仍然较大,则在此使用mongo的子模块GridFS来实现为这两种类型的上传截取代码

1、上传到本地服务器

@请求映射(value='/application/file/upload ', method=request method.post (publicobjectuoloadfile (@ request param ) ' file ) MultipartFile file ) returnbuildmessage } coade 现在回到前端的该文件保存后的相对路径,以下是服务层upload的具体实现:

公共字符串更新文件(多文件) throwsnotifyexception(/首先图像格式liststringimagetype=lists.new ArrayList ) () 获取文件名,后缀stringoriginalfilename=file.getoriginalfilename (; //文件后缀格式string file suffix=original filename.substring (original filename.lastindexof ('.' )1).toLowerCase ) if (imagetype.contains (file suffix )//仅在满足图像格式时进来,重新分配图像名称并防止名称重复的string new filename=uuidtypehandler.ccom //此方法返回当前项目的工作目录。 也就是说,在哪个位置启动的java线程string dirpath=system.getproperty (' user.dir ); string path=file.separator ' uploadimg ' file.separator new filename; 文件destfile=new file (dirpath path ); if (! estfile.getparentfile((.exists ) ) destFile.getParentFile () ).mkdirs ); (try ) file.transferto ) ) destfile; //向前端返回路径返回相对路径; }catch(ioexceptione ) log.error ) (uploadpicerror ); 返回空值; } } else { //错误的文件log.error (' the picture ' ssuffixisillegal ); thrownewnotifyexception (exception constants.file _ upload _ error; }上述代码是上传图像的例子,和上传文件一样,删除图像格式的验证即可

2、上传到MongoDB

这里采用其子模块GridFS的实现,代码对应用GridFsTemplate类实现,GridFS使用两个集合(collection )存储文件。 集合是chunks,用于存储文件内容的二进制数据。 集合是包含文件元数据和扩展数据的files。 将一个文件保存到GridFS时,如果文件大于chunksize (每个chunk块大小为256KB ),首先将文件按chunk大小划分为多个chunk块,然后最终将chun

k块的信息存储在fs.chunks集合的多个文档中。然后将文件信息存储在fs.files集合的唯一一份文档中。其中fs.chunks集合中多个文档中的files_id字段对应fs.files集中文档”_id”字段。

读文件时,先根据查询条件在files集合中找到对应的文档,同时得到“_id”字段,再根据“_id”在chunks集合中查询所有“files_id”等于“_id”的文档。最后根据“n”字段顺序读取chunk的“data”字段数据,还原文件。

整合MongoDB:

为了使本文更全面点,那么先讲springBoot如何整合mongo,由于springBoot默认是没有提供配置连接池的属性,即你在application.yaml中的连接配置是不带连接池功能,因此这里我建议采用代码方式进行配置mongo,同时代码中配置能更好的切换不同的数据库以创建不同的MongoDbFactory,先贴pom文件依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>

然后看下代码配置mongodb与springboot整合:

@Servicepublic class MongoConfig extends AbstractMongoConfiguration { @Override public MongoClient mongoClient() { MongoClient mongoClient = getMongoClient(); return mongoClient; } public MongoClient getMongoClient() { // MongoDB地址列表 List<ServerAddress> serverAddresses = new ArrayList<>(); serverAddresses.add(new ServerAddress("xxxx:27017")); // 连接认证 MongoCredential credential = MongoCredential.createCredential("xxx", "xx", "xxx".toCharArray()); MongoClientOptions.Builder builder = MongoClientOptions.builder(); //最大连接数 builder.connectionsPerHost(10); //最小连接数 builder.minConnectionsPerHost(0); //超时时间 builder.connectTimeout(1000*3); // 一个线程成功获取到一个可用数据库之前的最大等待时间 builder.maxWaitTime(5000); //此参数跟connectionsPerHost的乘机为一个线程变为可用的最大阻塞数,超过此乘机数之后的所有线程将及时获取一个异常.eg.connectionsPerHost=10 and threadsAllowedToBlockForConnectionMultiplier=5,最多50个线程等级一个链接,推荐配置为5 builder.threadsAllowedToBlockForConnectionMultiplier(5); //最大空闲时间 builder.maxConnectionIdleTime(1000*10); //设置池连接的最大生命时间。 builder.maxConnectionLifeTime(1000*10); //连接超时时间 builder.socketTimeout(1000*10); MongoClientOptions myOptions = builder.build(); MongoClient mongoClient = new MongoClient(serverAddresses, credential, myOptions); return mongoClient; } @Override protected String getDatabaseName() { return "xxxx"; } /** * 获取另一个数据库 * @return */ public String getFilesDataBaseName() { return "xxx"; } /** * 用于切换不同的数据库 * @return */ public MongoDbFactory getDbFactory(String dataBaseName) { MongoDbFactory dbFactory = null; try { dbFactory = new SimpleMongoDbFactory(getMongoClient(), dataBaseName); } catch (Exception e) { log.error("Get mongo client have an error, please check reason...", e.getMessage()); } return dbFactory; } /** * 获取文件存储模块 * @return */ public GridFsTemplate getGridFS() { return new GridFsTemplate(getDbFactory(getFilesDataBaseName()), mongoTemplate.getConverter()); }}

为了测试方便,各参数都直接写死了,建议写到配置文件中去(例如disconf),方便更改或扩展,这里需要注意的是继承的getDatabaseName()方法中返回的数据库为mongoTemplate默认使用的库,若需切换到第二个库,请看如下代码

public String upload(MultipartFile file) { // 拿到本文的重点类 GridFsTemplate gridFsTemplate = mongoConfig.getGridFS(); try { InputStream in = file.getInputStream(); String filename = file.getOriginalFilename(); String contentType = file.getContentType(); // 这是扩展属性,供不同的业务需求,日后可根据特地的参数进行查询 BasicDBObject dbObject = new BasicDBObject("name", "xj"); dbObject.put("key", "value"); String fileId = gridFsTemplate.store(in, filename, contentType, dbObject).toString(); return fileId; } catch (IOException e) { log.error("transfer in error ."); return null; } }

重点即为图上的store()方法,有多个重载方法,可自行选择。

到这里其实还未结束,springboot上传文件默认支持的大小为1mb,因此碧蓝的大雁超过这个限制是会报如下错:

修改文件上传的大小即可,在yaml文件下增加如下配置:

spring: servlet: multipart: #单个数据的大小 max-file-size: 100MB #总数据的大小 max-request-size: 100MB

 

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