使用Spring REST上传图像

时间:2013-08-18 16:57:39

标签: java json spring rest

我想使用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 

2 个答案:

答案 0 :(得分: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 commons库,但我不确定,现在也不记得了)

<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>

答案 1 :(得分:0)

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

Item::parent

JS

     <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>

Spring控制器

     $(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);

    }
});

}