spring boot html上传文件,springboot上传文件到本地服务器

packagecn.jiashubing.controller;importcn.jiashubing.common.StringConstants;importcn.jiashubing.result.ResultModel;importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importio.swagger.annotations.ApiParam;importorg.springframework.util.ResourceUtils;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;import java.io.*;importjava.text.SimpleDateFormat;importjava.util.Date;/***@authorjiashubing

*@since2019/6/25*/@RestController

@Api(tags= "稿件")

@RequestMapping(value=StringConstants.API)public classArticleController {

@ApiOperation("上传附件")

@RequestMapping(value= "/uploadFile", method =RequestMethod.POST)public ResultModel uploadFile(@RequestParam("file") @ApiParam(value = "二进制文件流") MultipartFile file) {

String fileName= file.getOriginalFilename();//获取文件名

fileName =getFileName(fileName);

String filepath=getUploadPath();if (!file.isEmpty()) {try (BufferedOutputStream out = newBufferedOutputStream(new FileOutputStream(new File(filepath + File.separator +fileName)))) {

out.write(file.getBytes());

out.flush();return new ResultModel<>(fileName);

}catch(FileNotFoundException e) {return new ResultModel<>(false, "上传文件失败 FileNotFoundException:" +e.getMessage());

}catch(IOException e) {return new ResultModel<>(false, "上传文件失败 IOException:" +e.getMessage());

}

}else{return new ResultModel<>(false, "上传文件失败,文件为空");

}

}/*** 文件名后缀前添加一个时间戳*/

privateString getFileName(String fileName) {int index = fileName.lastIndexOf(".");final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss"); //设置时间格式

String nowTimeStr = sDateFormate.format(new Date()); //当前时间

fileName = fileName.substring(0, index) + "_" + nowTimeStr +fileName.substring(index);returnfileName;

}/*** 获取当前系统路径*/

privateString getUploadPath() {

File path= null;try{

path= new File(ResourceUtils.getURL("classpath:").getPath());

}catch(FileNotFoundException e) {

e.printStackTrace();

}if (!path.exists()) path = new File("");

File upload= new File(path.getAbsolutePath(), "static/upload/");if (!upload.exists()) upload.mkdirs();returnupload.getAbsolutePath();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值