FileUploadUtil.java 4.2 KB
Newer Older
ZeGang Z Si's avatar
ZeGang Z Si committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
package pwc.taxtech.atms.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import pwc.taxtech.atms.common.config.FileServiceConfig;
import pwc.taxtech.atms.dto.ApiResultDto;
import pwc.taxtech.atms.exception.ServiceException;

import java.io.IOException;

/**
 * author kevin
 * ver 1.0
 */
@Configuration
public class FileUploadUtil  implements ApplicationContextAware {
    protected static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
    // Spring应用上下文环境
    private static ApplicationContext applicationContext;
    private  static FileServiceConfig config;
    private static final String USER_TEMPLATE_PATH = "pwc/userTemplate/";
    private static final String HTTP_HEADER = "application/json;charset=UTF-8";

    public static  String  upload(MultipartFile file) throws ServiceException{
        return  upload( file, false);
    }

    public static String serverPath(){
        config = (FileServiceConfig)applicationContext.getBean("fileServiceConfig");
        return  config.getServerUrl() + config.getUploadUrl();
    }
    /**
     * 上传模板
     *
     * @param file     MultipartFile
     * @param  fullPath 是否返回全路径 默认false ,如果为true返回的路径直接可以用于下载
     * @return Boolean
     */

    public  static String upload( MultipartFile file, boolean fullPath) throws ServiceException {
        if (StringUtils.isBlank(file.getOriginalFilename()) || null == file) {
            throw new IllegalArgumentException("上传参数为空");
        }
        CloseableHttpClient httpClient = null;
        String filePath = USER_TEMPLATE_PATH + file.getOriginalFilename();
        try {
            String serverPath = serverPath();
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(serverPath);
            httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

            JSONObject param = new JSONObject();
            param.put("path", filePath);
            param.put("file", file.getBytes());

            HttpEntity httpEntity = new StringEntity(param.toJSONString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(httpEntity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            ApiResultDto resultDto = JSON.parseObject(IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"), ApiResultDto.class);
            if (resultDto.getCode() == ApiResultDto.SUCCESS) {
kevin's avatar
kevin committed
78
                if(fullPath)
ZeGang Z Si's avatar
ZeGang Z Si committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
                    return config.getServerUrl() + "/" + filePath;
                return filePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("uploadTemplate error.", e);
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("close httpClient error.", e);
                }
            }
        }
        throw new ServiceException("uploadTemplate error.");
    }




    /**
     * 实现ApplicationContextAware接口的回调方法。设置上下文环境
     *
     * @param applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}