【问题标题】:Spring rest: upload fileSpring rest:上传文件
【发布时间】:2017-09-21 08:24:21
【问题描述】:

我正在使用此代码在我的 java 应用程序中使用 resteasy 上传文件,它运行良好。

import javax.ws.rs.FormParam;
import org.jboss.resteasy.annotations.providers.multipart.PartType;

public class FileUploadForm {

    public FileUploadForm() {
    }

    private byte[] data;

    public byte[] getData() {
        return data;
    }

    @FormParam("uploadedFile")
    @PartType("application/octet-stream")
    public void setData(byte[] data) {
        this.data = data;
    }

}

现在我想通过使用 spring boot 和 spring rest 来做同样的事情。 我搜索了很多关于如何在 spring rest 中使用 @FormParam@PartType 但我没有找到任何东西。

那么我怎样才能使用这个类来上传我的文件呢?弹簧休息中@PartType@FormParam 的等价物是什么?

【问题讨论】:

    标签: java file-upload spring-boot multipartform-data spring-rest


    【解决方案1】:

    你想在 spring rest 中编写一个文件上传的代码,它很简单,你只需要使用 multipart 文件对象,如下面的代码所示。

     @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA)
        public URL uploadFileHandler(@RequestParam("name") String name,
                                     @RequestParam("file") MultipartFile file) throws IOException {
    
    /***Here you will get following parameters***/
     System.out.println("file.getOriginalFilename() " + file.getOriginalFilename());
            System.out.println("file.getContentType()" + file.getContentType());
            System.out.println("file.getInputStream() " + file.getInputStream());
            System.out.println("file.toString() " + file.toString());
            System.out.println("file.getSize() " + file.getSize());
            System.out.println("name " + name);
            System.out.println("file.getBytes() " + file.getBytes());
            System.out.println("file.hashCode() " + file.hashCode());
            System.out.println("file.getClass() " + file.getClass());
            System.out.println("file.isEmpty() " + file.isEmpty());
    /***
    Bussiness logic
    ***/
    
    }
    

    【讨论】:

    • 是的。从这个参数你会得到该文件对象的所有可能信息。
    猜你喜欢
    • 2018-04-04
    • 2013-04-01
    • 2015-04-13
    • 2018-06-21
    • 2018-10-08
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多