java restful文件传输_Java文件上传:Restful接口接收上传文件,缓存在本地

该博客介绍了一个使用Java Restful接口接收并上传文件到本地的示例。在`FileController`类中,定义了一个POST请求的`/upload`接口,该接口接收`MultipartFile`类型的文件,然后通过`createLocalFile`方法将文件缓冲到指定的本地路径。文件被保存在Windows路径`F:/upload/temp`下,并在成功创建后返回确认信息。
摘要由CSDN通过智能技术生成

importlombok.extern.slf4j.Slf4j;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;import java.io.*;

@RestController

@RequestMapping(value= "/file")

@Slf4jpublic classFileController {/*** windows下的文件路径*/

private final String File_PATH = "F:/upload/temp";

@PostMapping(value= "/upload")

String uploadFileBufferToLocal(MultipartFile file) {//将文件缓冲到本地

boolean localFile =createLocalFile(File_PATH, file);if(!localFile){

log.error("Create local file failed!");return "Create local file failed!";

}

log.info("Create local file successfully");return "Create local file successfully";

}/*** 通过上传的文件名,缓冲到本地,后面才能解压、验证

*@paramfilePath 临时缓冲到本地的目录

*@paramfile*/

public booleancreateLocalFile(String filePath,MultipartFile file) {

File localFile= newFile(filePath);//先创建目录

localFile.mkdirs();

String originalFilename=file.getOriginalFilename();

String path= filePath+"/"+originalFilename;

log.info("createLocalFile path = {}", path);

localFile= newFile(path);

FileOutputStream fos= null;

InputStream in= null;try{if(localFile.exists()){//如果文件存在删除文件

boolean delete =localFile.delete();if (delete == false){

log.error("Delete exist file "{}" failed!!!",path,new Exception("Delete exist file ""+path+"" failed!!!"));

}

}//创建文件

if(!localFile.exists()){//如果文件不存在,则创建新的文件

localFile.createNewFile();

log.info("Create file successfully,the file is {}",path);

}//创建文件成功后,写入内容到文件里

fos = newFileOutputStream(localFile);

in=file.getInputStream();byte[] bytes = new byte[1024];int len = -1;while((len = in.read(bytes)) != -1) {

fos.write(bytes,0, len);

}

fos.flush();

log.info("Reading uploaded file and buffering to local successfully!");

}catch(FileNotFoundException e) {

e.printStackTrace();return false;

}catch(IOException e) {

e.printStackTrace();return false;

}finally{try{if(fos != null) {

fos.close();

}if(in != null) {

in.close();

}

}catch(IOException e) {

log.error("InputStream or OutputStream close error : {}", e);return false;

}

}return true;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值