SpringMVC文件下载

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2018/4/3.
 */
@Controller
public class Filedownload {

        @RequestMapping("/download")
        public ResponseEntity<byte[]> download() throws IOException {
            //下载文件路径
            String path="D:\测试.xls";
            File file=new File(path);
            //Http请求头
            HttpHeaders headers = new HttpHeaders();
            //为了解决中文名称乱码问题
            String fileName=new String("测试.xls".getBytes("UTF-8"),"iso-8859-1");
            //设置请求标题
            headers.setContentDispositionFormData("attachment", fileName);
            //按照标题中的指定设置正文的媒体类型
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.CREATED);
        }

}

  

原文地址:https://www.cnblogs.com/xuchangqi1/p/8709751.html