Spring boot: 读取服务端指定位置文件并返回

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    @Autowired
    ResourceLoader loader;

    // get image
    @RequestMapping(value="/getImage", produces = MediaType.IMAGE_JPEG_VALUE)
    public @ResponseBody byte[] getImage() {
        // specify image path
        String imagePath = "/usr/local/share/image/test.jpg"; 

        return IOUtils.toByteArray(loader.getResource("file:" + imagePath).getInputStream());
    }
    
    // load static resource of project
    @RequestMapping(value="/getImage", produces = MediaType.IMAGE_JPEG_VALUE)
    public @ResponseBody byte[] getImage() {
        // 假设静态资源目录结构如附件Screenshot_1所示
        return IOUtils.toByteArray(loader.getResource("classpath:static/image/test.png").getInputStream());
    }


    // download file form server
    @GetMapping("/getFile")
    public ResponseEntity<byte[]> getFile() {
        // specify file path
        String filePath = "/usr/local/share/audio/test.mp3";

        byte[] body = IOUtils.toByteArray(loader.getResource("file:" + filePath).getInputStream());
	String fileName = filePath.substring(filePath.lastIndexOf('/')+1, filePath.length());
	HttpHeaders headers=new HttpHeaders();
	headers.add("Content-Disposition", "attachment;filename="+fileName);

	return new ResponseEntity(body, headers, HttpStatus.OK);
    }
}



猜你喜欢

转载自pengyao0305.iteye.com/blog/2418751