java boot 文件传输_Java spring boot 实现文件上传

1、application.xml写相关配置

upload:

path: d:\\image\\

domain: http://images.xxx.com

temp: D:\\temp\\

2、编写接口

import java.io.InputStream;

/**

* 文件上传

*/

public interface IUploadService {

/**

* 上传文件

*

* @param inputStream

* @return

*/

String upload(InputStream inputStream, String fileName, String uploadType);

}

3、编写实现类

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.io.*;

import java.util.UUID;

@Service

public class UploadServiceImpl implements IUploadService {

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

private String uploadPath;

@Value("${upload.domain}")

private String fileDomain;

@Override

public String upload(InputStream inputStream, String fileName, String uploadType) {

OutputStream os = null;

try {

//保证文件夹存在

isCreateDir(uploadType);

//重新生成文件名称

String saveFileName = UUID.randomUUID() + getFileExtension(fileName);

File file = new File(uploadPath + uploadType + File.separator + saveFileName);

//循环读取输入流文件内容,通过输出流将内容写入新文件

os = new FileOutputStream(file);

byte buffer[] = new byte[1024];

int cnt = 0;

while ((cnt = inputStream.read(buffer)) > 0) {

os.write(buffer, 0, cnt);

}

System.out.print(fileDomain + "/" + uploadType + "/" + saveFileName);

return fileDomain + "/" + uploadType + "/" + saveFileName;

} catch (FileNotFoundException e) {

e.printStackTrace();

throw new SuperKindRunTimeException("文件不存在");

} catch (IOException e) {

e.printStackTrace();

throw new SuperKindRunTimeException("IO异常");

} finally {

if (os != null) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (inputStream != null) {

try {

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/**

* 获取文件扩展名

*

* @param fileName

* @return

*/

private String getFileExtension(String fileName) {

String extension = fileName;

if (fileName.lastIndexOf(".") != -1) {

extension = "." + extension.substring(extension.lastIndexOf(".") + 1);

} else {

extension = "";

}

return extension;

}

private void isCreateDir(String uploadType) {

File file = new File(uploadPath + uploadType);

//如果文件夹不存在,则新建

if (!file.exists()) {

file.mkdirs();

}

}

}

4、调用接口就OK

@Autowired

private IUploadService uploadService;

@Override

public String insertAdjunctByEnquiry(MultipartFile file) {

try{

String uploadType = "customer-files";

String uploadPath = uploadService.upload(file.getInputStream(), file.getOriginalFilename(), uploadType);

return uploadPath;

}catch (Exception e){

e.printStackTrace();

}

return null;

}

5、结果

31e526b5dd9c

本地图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值