java http接口服务端接收文件夹_Java客户端服务端上传接收文件实现详解

Java客户端通过HTTP协议上传文件, 服务端处理客户端请求, MultipartFile转File, 实现客户端上传文件的存储

Java环境: JDK1.8

开发环境: IDEA

SpringBoot: 2.2.0

Maven: 3.6.3

Java客户端通过HTTP协议上传文件

// 引入pom依赖, hutool相关文档, https://www.hutool.cn/docs/

cn.hutool

hutool-all

5.3.7

HashMap paramMap = new HashMap<>();

//文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别

paramMap.put("file", FileUtil.file("C:\\文件路径\\文件名称"));

String result = HttpUtil.post("服务端IP:端口", paramMap);

Java服务端接收请求并实现文件的存储

工具类

public class Utils {

public static void saveFile( MultipartFile filecontent){

OutputStream os = null;

InputStream inputStream = null;

String fileName = null;

try {

inputStream = filecontent.getInputStream();

fileName = filecontent.getOriginalFilename();

} catch (IOException e) {

e.printStackTrace();

}

try {

String path = "C:\\test\\";

// 2、保存到临时文件

// 1K的数据缓冲

byte[] bs = new byte[1024];

// 读取到的数据长度

int len;

// 输出的文件流保存到本地文件

File tempFile = new File(path);

if (!tempFile.exists()) {

tempFile.mkdirs();

}

os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);

// 开始读取

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

os.write(bs, 0, len);

}

} catch (IOException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

// 完毕,关闭所有链接

try {

os.close();

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

Controller类

@Controller

public class FileController {

@RequestMapping("/")

@ResponseBody

public String index(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {

Utils.saveFile(file);

return "Success";

}

}

注意:

文件较大时spring-boot 服务端报上传文件错误“spring.servlet.multipart.max-file-size”

可以修改配置文件: application.properties, 添加以下配置..大小自行修改...

spring.servlet.multipart.max-file-size=200MB

spring.servlet.multipart.max-request-size=200MB

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值