使用restTemplate上传文件

本文详细介绍了一种基于RESTful的文件上传方案,包括服务端与客户端的实现过程。通过restTemplate实现文件从客户端到服务端的传输,并展示了如何在服务端处理上传的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单介绍

既然使用到了restTemplate,肯定分为两部分:
	1、客户端(分点服务器)
	2、服务端(管理服务器)

演示图

文件路径这里并未更改路径,只是放到了临时文件中,需要用到文件也方便,后续会改个单模块的上传版本

在这里插入图片描述

核心代码(服务端)

controller类

@RequestMapping(value = "toImport")
    public ResponseEntity tpImpl(MultipartFile fileUpload, HttpServletRequest request)throws IOException{
        RestTemplate restTemplate = new RestTemplate();
        //获取临时文件
        String tempFilePath = System.getProperty("java.io.tmpdir")+fileUpload.getOriginalFilename();
        File file = new File(tempFilePath);
        fileUpload.transferTo(file);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        httpHeaders.setContentType(MediaType.parseMediaType("multipart/form-data;charset=UTF-8"));
        MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();
        //把临时文件转换成FileSystemResource
        FileSystemResource resource = new FileSystemResource(tempFilePath);
        param.add("fileUpload",resource);//	对应客户端的接收参数名称
        HttpEntity<MultiValueMap<String,Object>> formEntity = new HttpEntity<>(param,httpHeaders);
        String imports = String.format("http://%s:%s/client/toImportFile", request.getParameter("ip"), request.getParameter("port"));
        ResponseEntity responseEntity = restTemplate.postForEntity(imports, formEntity, Result.class);
        log.info("tempFilePath={}",tempFilePath );
        return new ResponseEntity(responseEntity.getBody(), HttpStatus.OK);
    }

工具类

public class Result<T> {
    //代码
    private int code;
    //提示信息
    private String message;
    //具体内容
    private T data;

    // 是否成功
    private boolean success;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public Result(T data, boolean success) {
        this.data = data;
        this.success = success;
    }

    public Result() {
    }
}

前端页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>FileUpload Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <link th:href="@{/css/bootstrap.min.css}" href="../static/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link th:href="@{/css/fileinput/fileinput.min.css}" href="../static/css/fileinput/fileinput.min.css"
          rel="stylesheet" type="text/css">
    <link th:href="@{/css/font-awesome.css}" href="../static/css/font-awesome.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2" style="margin-top: 7%">
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <input id="fileUpload" name="fileUpload" class="file" type="file" data-preview-file-type="text">
                        <div id="tip-warn" class="alert alert-warning fade in" style="margin-top: 10px;display: none">

                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</body>
<script th:src="@{/js/jquery.min.js}" src="../static/js/jquery.min.js"></script>
<script th:src="@{/js/bootstrap.min.js}" src="../static/js/bootstrap.min.js"></script>
<script th:src="@{/js/plugins/fileinput/fileinput.min.js}" src="../static/js/plugins/fileinput/fileinput.min.js"></script>
<script>
    var ip = "[[${ip}]]";
    var port = [[${port}]];
    $("#fileUpload").fileinput({
        uploadUrl: 'toImport',
        allowedFileExtensions: ['txt'],
        maxFileCount: 1,
        uploadExtraData: function () {   //额外参数的关键点
            var obj = {
                ip: ip,
                port: port
            };
            return obj;
        }
    }).on('fileuploaded', function (event, data, id, index) {


    }).on('fileuploaderror', function (event, data, msg) {

    });
</script>
</html>

核心代码(客户端)

controller类

@Controller
@Slf4j
@RequestMapping(value = "client")
public class FileUploadController {

    @RequestMapping(value = "/toImportFile")
    public ResponseEntity toImpl(MultipartFile fileUpload) {
        if (fileUpload != null) {
            try {
                BufferedReader br = null;
                StringBuffer sb;
                br = new BufferedReader(new InputStreamReader(fileUpload.getInputStream()));
                String temp = null;
                sb = new StringBuffer();
                try {
                    temp = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                while (temp != null) {
                    sb.append(temp + "\n");
                    try {
                        temp = br.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info("upload success");
                return new ResponseEntity(new Result(null, true), HttpStatus.OK);
            } catch (IOException e) {
                e.printStackTrace();
                return new ResponseEntity(new Result(null, false), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            return new ResponseEntity(new Result(null, true), HttpStatus.FAILED_DEPENDENCY);
        }
    }

}

客户端的工具类Result可复用服务端的Result内容

答疑

如有问题可留言,一起讨论

源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值