spring boot 文件处理——迹忆客-ag捕鱼王app官网

在本章中,我们将学习如何使用 web 服务上传和下载文件。


文件上传

对于上传文件,我们可以使用 multipartfile 作为请求参数,此 api 应使用 multi-part 表单数据值。 观察下面给出的代码

@requestmapping(value = "/upload", method = requestmethod.post, consumes = mediatype.multipart_form_data_value)
public string fileupload(@requestparam("file") multipartfile file) {
   return null;
}

下面给出了相同的完整代码

package com.study.controller;
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
/**
 * @author jiyik.com
 */
@restcontroller
public class fileuploadcontroller {
    @requestmapping(value = "/upload", method = requestmethod.post, consumes = mediatype.multipart_form_data_value)
    public string fileupload(@requestparam("file") multipartfile file) throws ioexception {
        file convertfile = new file("/tmp/" file.getoriginalfilename());
        convertfile.createnewfile();
        fileoutputstream fout = new fileoutputstream(convertfile);
        fout.write(file.getbytes());
        fout.close();
        return "文件上传成功";
    }
}

文件下载

对于文件下载,我们应该使用 inputstreamresource 下载文件。 我们需要在 response 中设置httpheader content-disposition ,并且需要指定应用的响应media type

注意 - 在以下示例中,文件应该在应用程序运行的指定路径上可用

@requestmapping(value = "/download", method = requestmethod.get)
public responseentity
网站地图