当前位置:   article > 正文

使用restTemplate上传文件_resttemplate上传multipartfile

resttemplate上传multipartfile

简单介绍

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

演示图

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

在这里插入图片描述

核心代码(服务端)

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);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

工具类

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() {
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

前端页面

<!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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

核心代码(客户端)

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);
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

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

答疑

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

源码下载

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/302886
推荐阅读
相关标签
  

闽ICP备14008679号