package com.tjk.controller;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tjk.dao.AttachmentMapper;
import com.tjk.entity.Attachment;

@Controller
public class AttachmentController {
	@Resource
	private AttachmentMapper attachmentMapper;

	// 附件下载
	@RequestMapping("api/attachment/download.do")
	@ResponseBody
	public HttpServletResponse downloadAttachment(HttpServletRequest request,
			HttpServletResponse response, Integer attachmentId) {
		Attachment atta = attachmentMapper.findAttachmentById(attachmentId);
		if (atta != null) {
			try {
				String path = "";
				String temp = request.getServletContext().getRealPath("");
				temp = temp.substring(0, temp.lastIndexOf("\\") + 1);
				if (atta.getAttachmentType() == 2) {
					path = temp + "/" + atta.getUri();
				} else {
					path = temp + atta.getUri();
				}
				// path是指欲下载的文件的路径。
				File file = new File(path);
				String fileName = file.getName();
				// 取得文件的后缀名。
				String ext = fileName.substring(fileName.lastIndexOf(".") + 1)
						.toUpperCase();
				// 以流的形式下载文件。
				InputStream fis = new BufferedInputStream(new FileInputStream(
						path));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				// 清空response
				response.reset();
				// 设置response的Header
				response.addHeader("Content-Disposition",
						"attachment;filename="
								+ new String(fileName.getBytes()));
				response.addHeader("Content-Length", "" + file.length());
				OutputStream toClient = new BufferedOutputStream(
						response.getOutputStream());
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
			} catch (IOException ex) {
				ex.printStackTrace();
				try {
					response.sendError(404, "文件不存在");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			try {
				response.sendError(404, "文件不存在");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}
}
