1

我想使用 RestTemplate 客户端上传图像并使用 Spring 基本 REST 服务器获取该 POST 请求并保存在服务器上。任何人都可以帮助我如何使用我的 Spring 基础客户端和服务器来做到这一点。谢谢

我的一些 Spring REST API 基础服务器方法如下,

@RequestMapping(value="user/upload/{imageFile}", method=RequestMethod.POST)
    public @ResponseBody User upload(@RequestBody User user, @PathVariable File imageFile, HttpServletResponse response) {

 // TODO - How I get this image and file and save, whether I can POST this image file with User object 

 }

我的一些远程客户端的 Spring RestTemplate 基本代码如下,

User newUser = new User();

Map<String, String> vars = new HashMap<String, String>();
            vars.put("imageFile", imageFile);

            ResponseEntity<User> REcreateUser = restTemplate.postForEntity(IMC_LAB_SKELETON_URL + "/user/upload/{imageFile}", newUser, User.class, vars);

            User createUser = REcreateUser.getBody();

// TODO - How I can POST this image file as a parameter or content of the User object 
4

2 回答 2

3

这是我之前写的一段代码(你可以将文件名作为@PathVariable 传递):

服务器端:

@RequestMapping(value = "/file", method = RequestMethod.POST)
public String uploadFile(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
            //add your logics here
            //File newFile = new File("blablabla.xxx");
            //file.transferTo(newFile);
...

使用休息模板进行测试:

@Test
public void testFileUpload() {

    String url = "http://blablabla.com/file";

    Resource resource = new ClassPathResource("images/file.xxx");

    MultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
    mvm.add("file", resource);

    ResponseEntity<String> respEnt = rt.postForEntity(url, mvm, String.class);

    //logger.info("body: " + respEnt.getBody());
... 

需要这个 bean(我认为它需要一些 apache 公共库,但我不确定,现在不记得了)

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="500000"/>
    </bean>
于 2013-08-18T19:41:43.240 回答
0

参考下面的代码你可以上传多个文件,工作正常

     <form method="POST" enctype="multipart/form-data"
                    id="fileUploadForm">
                    <div class="controls">
                        <div class="entry input-group col-xs-3">
                            <input class="btn btn-primary" name="files" type="file">
                            <span class="input-group-btn">
                                <button class="btn btn-success btn-add" type="button">
                                    <span class="glyphicon glyphicon-plus"></span>
                                </button>
                            </span>
                        </div>
                    </div>
                </form>

JS

     $(document).ready(function() {

$("#btnSubmit").click(function(event) {

    // stop submit the form, we will post it manually.
    event.preventDefault();

    fire_ajax_submit();

});

});

 function fire_ajax_submit() {

// Get form
var form = $('#fileUploadForm')[0];

var data = new FormData(form);

data.append("CustomField", "This is some extra data, testing");

// $("#btnSubmit").prop("disabled", true);
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});

$.ajax({
    method : "POST",
    enctype : 'multipart/form-data',
    url : "lotConfig/lotImage",
    data : data,
    // http://api.jquery.com/jQuery.ajax/
    // https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
    processData : false, // prevent jQuery from automatically
    // transforming the data into a query string
    contentType : false,
    cache : false,
    timeout : 600000,
    success : function(data) {

        jQuery('#lotImageget').html('');
        getAllLotiamges();
        $('#updateImage').modal('hide');

        /*
         * $("#result").text(data); console.log("SUCCESS : ", data);
         * $("#btnSubmit").prop("disabled", false);
         */

    },
    error : function(e) {

        $("#result").text(e.responseText);
        console.log("ERROR : ", e);
        // $("#btnSubmit").prop("disabled", false);

    }
});

}

弹簧控制器

      @PostMapping(value = "/lotImage")
        public ResponseEntity<String> updateLotImage(
        @RequestParam("files") MultipartFile[] files,
        RedirectAttributes redirectAttributes, HttpSession session)
        throws IOException {
    logger.info("--got request to update Lot Image--");
    StringJoiner sj = new StringJoiner(" , ");
    for (MultipartFile file : files) {
        if (file.isEmpty()) {
            continue; // next pls
        }
        try {

            byte[] bytes = file.getBytes();
            Properties prop = new Properties();
            String resourceName = "app.properties";
            ClassLoader loader = Thread.currentThread()
                    .getContextClassLoader();
            InputStream resourceStream = loader
                    .getResourceAsStream(resourceName);
            try {
                prop.load(resourceStream);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String image_path = prop.getProperty("LOT_DESTINATION_IMG");

            Path path = Paths.get(image_path
                    + file.getOriginalFilename());
            Files.write(path, bytes);

            sj.add(file.getOriginalFilename());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    logger.info("--Image updated--");
    return new ResponseEntity<String>("Success", HttpStatus.OK);

}
于 2018-02-06T12:00:06.393 回答