网站上传图片、文件等,七牛云3.自己搭建文件存储服务器

优采云 发布时间: 2021-04-01 21:01

  网站上传图片、文件等,七牛云3.自己搭建文件存储服务器

  网站上传图片,文件等。最常见的方法是将它们直接上传到服务器的webapp目录,或直接上传到服务的指定文件夹。对于简单的独立应用程序,此方法确实非常方便且简单,并且问题较少。但是,对于分布式项目,直接上载到项目路径的方法显然是不可靠的,并且随着业务量的增加,文件将增加,并且服务器上的压力自然会增加。这是对您了解的有关保存文件的几种方式的简要介绍。

  1.直接上传到指定的服务器路径;

  2.上传到第三方内容存储,这是将图片保存到Qiniu Cloud的方法

  3.构建自己的文件存储服务器,例如FastDFS,FTP服务器等。

  最简单的上传

  首先,解释项目结构为SpringBoot + mybatis。由于该项目以jar形式打包,因此图片保存在此处的指定目录中。

  添加WebAppConfig配置类

  @Configuration

public class WebAppConfig extends WebMvcConfigurerAdapter{

/**

* 在配置文件中配置的文件保存路径

*/

@Value("${img.location}")

private String location;

@Bean

public MultipartConfigElement multipartConfigElement(){

MultipartConfigFactory factory = new MultipartConfigFactory();

//文件最大KB,MB

factory.setMaxFileSize("2MB");

//设置总上传数据总大小

factory.setMaxRequestSize("10MB");

return factory.createMultipartConfig();

}

}

  文件上传的方法。此方法的某些参数可能需要简单地修改。通常,首先使用文件保存路径处理文件,然后将文件保存到该路径,最后返回文件上传信息。

   @PutMapping("/article/img/upload")

public MarkDVo uploadImg(@RequestParam("editormd-image-file") MultipartFile multipartFile) {

if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {

throw new BusinessException(ResultEnum.IMG_NOT_EMPTY);

}

String contentType = multipartFile.getContentType();

if (!contentType.contains("")) {

throw new BusinessException(ResultEnum.IMG_FORMAT_ERROR);

}

String root_fileName = multipartFile.getOriginalFilename();

logger.info("上传图片:name={},type={}", root_fileName, contentType);

//处理图片

User currentUser = userService.getCurrentUser();

//获取路径

String return_path = ImageUtil.getFilePath(currentUser);

String filePath = location + return_path;

logger.info("图片保存路径={}", filePath);

String file_name = null;

try {

file_name = ImageUtil.saveImg(multipartFile, filePath);

MarkDVo markDVo = new MarkDVo();

markDVo.setSuccess(0);

if(StringUtils.isNotBlank(file_name)){

markDVo.setSuccess(1);

markDVo.setMessage("上传成功");

markDVo.setUrl(return_path+File.separator+file_name);

markDVo.setCallback(callback);

}

logger.info("返回值:{}",markDVo);

return markDVo;

} catch (IOException e) {

throw new BusinessException(ResultEnum.SAVE_IMG_ERROE);

}

}

  文件保存类

   /**

* 保存文件,直接以multipartFile形式

* @param multipartFile

* @param path 文件保存绝对路径

* @return 返回文件名

* @throws IOException

*/

public static String saveImg(MultipartFile multipartFile,String path) throws IOException {

File file = new File(path);

if (!file.exists()) {

file.mkdirs();

}

FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();

String fileName = Constants.getUUID() + ".png";

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));

byte[] bs = new byte[1024];

int len;

while ((len = fileInputStream.read(bs)) != -1) {

bos.write(bs, 0, len);

}

bos.flush();

bos.close();

return fileName;

}

  配置文件保存路径

  

  测试:直接使用邮递员上传

  

  

  以下需要访问和预览上传的图片

  在配置文件中添加静态资源的配置。 SpringBoot对静态的处理,Springboot的静态资源路径配置

  

  然后在浏览器的链接栏中键入:图片应在此处忽略

  

  上传到Qiniu Cloud

  在这里,您必须首先在Qiniu Cloud中注册一个帐户并打开对象存储空间。免费用户拥有10G的存储空间。教程:

  然后在您自己的项目中设置环境:使用maven指导软件包

  

com.qiniu

qiniu-java-sdk

[7.2.0, 7.2.99]

  然后找到刚才创建的密钥,将其复制并保存在项目资源文件中

  

  此处的存储桶是上面存储空间的名称,而路径是域名。

  

  上传工具:

  @Component

public class QiniuUtil{

private static final Logger logger = LoggerFactory.getLogger(QiniuUtil.class);

@Value("${qiniu.accessKey}")

private String accessKey;

@Value("${qiniu.secretKey}")

private String secretKey;

@Value("${qiniu.bucket}")

private String bucket;

@Value("${qiniu.path}")

private String path;

/**

* 将图片上传到七牛云

* @param file

* @param key 保存在空间中的名字,如果为空会使用文件的hash值为文件名

* @return

*/

public String uploadImg(FileInputStream file, String key) {

//构造一个带指定Zone对象的配置类

Configuration cfg = new Configuration(Zone.zone1());

//...其他参数参考类注释

UploadManager uploadManager = new UploadManager(cfg);

//...生成上传凭证,然后准备上传

// String bucket = "oy09glbzm.bkt.clouddn.com";

//默认不指定key的情况下,以文件内容的hash值作为文件名

try {

Auth auth = Auth.create(accessKey, secretKey);

String upToken = auth.uploadToken(bucket);

try {

Response response = uploadManager.put(file, key, upToken, null, null);

//解析上传成功的结果

DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

// DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

// System.out.println(putRet.key);

// System.out.println(putRet.hash);

String return_path = path+"/"+putRet.key;

logger.info("保存地址={}",return_path);

return return_path;

} catch (QiniuException ex) {

Response r = ex.response;

System.err.println(r.toString());

try {

System.err.println(r.bodyString());

} catch (QiniuException ex2) {

//ignore

}

}

} catch (Exception e) {

e.printStackTrace();

}

return "";

}

}

  上传界面方法

  

/**

* 上传文件到七牛云存储

* @param multipartFile

* @return

* @throws IOException

*/

@PutMapping("/article/img/qiniu")

public String uploadImgQiniu(@RequestParam("editormd-image-file") MultipartFile multipartFile) throws IOException {

FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();

User currentUser = userService.getCurrentUser();

String path = qiniuUtil.uploadImg(inputStream, currentUser.getUsername()+"_"+Constants.getUUID());

return path;

}

  测试

  

  

  将文件上传到FastDFS

  首先,您需要构建一个FastDFS服务器,这里将不再介绍。门户:Linux下FastDFS系统的构建

  依赖性

  

com.github.tobato

fastdfs-client

1.25.4-RELEASE

  添加配置信息

  

  FastDFS配置类

  @Configuration

@ComponentScan(value = "com.github.tobato.fastdfs.service")

@Import(FdfsClientConfig.class)

@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)

public class FastDfsConfig {

}

  这里,FastDFS文件的操作仅处理上传,上传文件类型:

   @Autowired

private FastFileStorageClient storageClient;

@Autowired

private FdfsWebServer fdfsWebServer;

@PutMapping("/article/img/fdfs")

public String uploadImgfdfs(@RequestParam(value = "editormd-image-file") MultipartFile multipartFile) throws IOException {

StorePath storePath= storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), "png", null);

String path = storePath.getFullPath();

logger.info("保存路径={}",path);

return path;

}

  测试:

  

  参考:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线