package com.engine.htsc.uploadfile.web;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class UploadFileAction {

    @POST
    @Path("/uploadfile")
    @Produces(MediaType.TEXT_PLAIN)
    public String uploadfile(@Context HttpServletRequest request, @Context HttpServletResponse response){

        Map<String,Object> apidatas = new HashMap<String,Object>();

        String fileName = request.getParameter("fileName");
        System.out.println("filename:"+fileName);
        String fileparth = "/usr/appadmin/video/" ;
        String fileFullPath = fileparth + fileName;

        InputStream ins = null;
        FileOutputStream fos = null;
        try {
            ins = request.getInputStream();
            File file = new File(fileparth);
            if(!file.exists()){
                file.mkdirs();
            }
            fos = new FileOutputStream(fileFullPath);
            int size = 0;
            int byteLength = 8196;
            byte[] buffer = new byte[byteLength];
            while ((size = ins.read(buffer,0,byteLength)) != -1) {
                fos.write(buffer, 0, size);
            }
            fos.close();
            ins.close();

            apidatas.put("filepath", fileparth);
            apidatas.put("api_status", true);
        } catch (IOException e) {
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        } finally{
            try {
                if(ins != null){
                    ins.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(fos != null){
                    fos.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSONObject.toJSONString(apidatas);
    }

}
