package com.apobates.forum.utils.fileupload;

import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.fileupload.FileItem;
/**
 * apache commons fileupload实现
 * @author xiaofanku@live.cn
 * @since 20171216
 */
public class ApacheFileUploadConnector extends AbstractUploadConnector{
    private final static Logger logger=LoggerFactory.getLogger(ApacheFileUploadConnector.class);
    
    public ApacheFileUploadConnector(UploadHandler handler){
        super(handler);
    }
    
    protected String execute(FileItem fileItem, File uploadDir, String callFuntion) throws IOException {
        String redata="-1";
        //是不是HTML常规输入项
        boolean isFormField = fileItem.isFormField();
        String saveFileName=(getHandler().generateFileName()!=null)?getHandler().generateFileName():fileItem.getName();
        if (!isFormField) {
            super.checkFileExtension(fileItem.getName());
            super.checkFileByteSize(fileItem.getSize());
            //开始保存文件
            File uploadedFile=new File(uploadDir, saveFileName);
            try{
                fileItem.write(uploadedFile);
            }catch(Exception e){
                if (logger.isDebugEnabled()) {
                    logger.debug("apache commons fileupload save file fail", e);
                }
                getHandler().forceException(new IOException(e.getMessage()));
            }
            String descrip = "" + NEWLINE;
            descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
            descrip += "/* FIELD NAME:" + fileItem.getFieldName() + NEWLINE;
            descrip += "/* Name:" + fileItem.getName() + NEWLINE;
            descrip += "/* CONTENT TYPE:" + fileItem.getContentType() + NEWLINE;
            descrip += "/* SIZE:" + fileItem.getSize() + " (Bytes)" + NEWLINE;
            descrip += "/* Directory:" + uploadedFile.getAbsolutePath() + NEWLINE;
            descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
            if (logger.isDebugEnabled()) {
                logger.debug(descrip);
            }
            //path
            redata=getHandler().getResponse(saveFileName, callFuntion);
        }
        getHandler().otherProcess(uploadDir, saveFileName, callFuntion);
        return redata;
    }
}
