package com.uas.platform.b2b.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uas.platform.b2b.model.Attach;
import com.uas.platform.b2b.service.AttachService;

/**
 * 平台文件
 * 
 * @author yingp
 *
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@Autowired
	private AttachService attachService;

	/**
	 * 文件下载
	 * 
	 * @param fileId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/{fileId}")
	public void download(@PathVariable("fileId") long fileId, HttpServletResponse response) throws IOException {
		Attach attch = attachService.getAttach(fileId);
		File file = new File(attch.getPath());
		InputStream in = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		response.addHeader("Content-Disposition", "attachment;filename=" + new String(attch.getName().getBytes("utf-8"), "iso-8859-1"));
		response.addHeader("Content-Length", String.valueOf(file.length()));
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/octec-stream");
		int data = 0;
		while ((data = in.read()) != -1) {
			os.write(data);
		}
		in.close();
		os.close();
	}

}
