java后端上传下载文件

原创
2018/06/20 21:24
阅读数 1.5K
package com.weshare.argus.service.impl;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weshare.argus.common.adapter.RestTemplateUtil;
import com.weshare.argus.common.config.SystemConfig;
import com.weshare.argus.common.contants.Constant;
import com.weshare.argus.service.UploadService;
import com.weshare.argus.utils.Result;
import com.weshare.argus.utils.WeshareTokenHelper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 陈稳 on 2018/6/15.
 */
@Service
public class UploadServiceImpl implements UploadService {
    private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Override
    public void uploadFile(MultipartFile file, String paramJson, String originalUrl) throws Exception {
        try {
            // 1-1, 根据originalUrl解析服务器名,urlSuffix
            if (originalUrl.startsWith("/") && originalUrl.length() > 1) {
                originalUrl = originalUrl.substring(1);
            }
            // 获取服务项目名
            String projectName = originalUrl.substring(0, originalUrl.indexOf("/"));
            String urlSuffix = originalUrl.substring(originalUrl.indexOf("/"));

            // 1-2,根据服务项目名获取对应的ak,sk
            // 根据服务器项目名获取想对应的url,ak,sk等信息
            String urlPrefix = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_URL_COMMON);
            String requestUrl = urlPrefix + originalUrl;
            String ak = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_AK_COMMON);
            String sk = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_SK_COMMON);

            TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
            SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

            if (StringUtils.isEmpty(paramJson)) {
                paramJson = sk;
            }
            int expireTime = (int) (System.currentTimeMillis() / 1000 + 30 * 60);
            WeshareTokenHelper tokenHelper = new WeshareTokenHelper(ak, sk);
            // 设置消息头
            String generateToken = tokenHelper.generateToken(urlSuffix, "POST", "", paramJson, expireTime);

            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(requestUrl);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("paramJson", paramJson, ContentType.APPLICATION_JSON);
            builder.addTextBody("token", generateToken, ContentType.APPLICATION_JSON);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                logger.info("uploadFile | Result is : {}" + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public void downloadFile(HttpServletResponse response, String paramJson, String originalUrl) throws Exception {
        try {
            // 1-1, 根据originalUrl解析服务器名,urlSuffix
            if (originalUrl.startsWith("/") && originalUrl.length() > 1) {
                originalUrl = originalUrl.substring(1);
            }
            // 获取服务项目名
            String projectName = originalUrl.substring(0, originalUrl.indexOf("/"));
            String urlSuffix = originalUrl.substring(originalUrl.indexOf("/"));

            // 1-2,根据服务项目名获取对应的ak,sk
            // 根据服务器项目名获取想对应的url,ak,sk等信息
            String urlPrefix = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_URL_COMMON);
            String requestUrl = urlPrefix + originalUrl;
            String ak = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_AK_COMMON);
            String sk = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_SK_COMMON);

            if (StringUtils.isEmpty(paramJson)) {
                paramJson = sk;
            }
            int expireTime = (int) (System.currentTimeMillis() / 1000 + 30 * 60);
            WeshareTokenHelper tokenHelper = new WeshareTokenHelper(ak, sk);
            // 设置消息头
            String generateToken = tokenHelper.generateToken(urlSuffix, "POST", "", paramJson, expireTime);



            // 设置消息头
            Map<String, String> headers = new HashMap<>(10);
            // 设置请求体
            JSONObject bodyObj = new JSONObject();
            bodyObj.put("token", generateToken);
            if (!StringUtils.isEmpty(paramJson)) {
                bodyObj.put("paramJson", paramJson);
            } else {
                bodyObj.put("paramJson", sk);
            }
            ResponseEntity<byte[]> responseEntity  = restTemplateUtil.postForEntity2(requestUrl, headers, bodyObj);
            // 如果结果返回正常的情况下下载文件
            if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
                byte[] result = responseEntity.getBody();
                HttpHeaders httpHeaders = responseEntity.getHeaders();
                String contentType = String.valueOf(responseEntity.getHeaders().getContentType());
                List<String> contentDispositon = httpHeaders.get("content-disposition");
                response.setContentType(contentType);
                response.setHeader("content-disposition", contentDispositon.get(0));
                OutputStream toClient = response.getOutputStream();
                toClient.write(result);
                toClient.flush();
            } else {
                logger.error("downloadFile failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
package com.weshare.argus.common.adapter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * <类功能简述>
 *
 * @author chenwen
 */
@Component
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;

    public<I> ResponseEntity<JSONObject> postForEntity(String url, Map<String, String> headerMap, I input) {

        // 设置消息头
        HttpHeaders headers = new HttpHeaders();

        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }

        // 设置请求参数
        HttpEntity httpEntity = new HttpEntity<>(input, headers);

        return restTemplate.postForEntity(url, httpEntity, JSONObject.class);
    }

    public<T> ResponseEntity<byte[]> postForEntity2(String url, Map<String, String> headerMap, T input) {

        // 设置消息头
        HttpHeaders headers = new HttpHeaders();

        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }

        // 设置请求参数
        HttpEntity httpEntity = new HttpEntity<>(input, headers);

        return restTemplate.postForEntity(url, httpEntity, byte[].class);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <!--rest template config-->
    <bean id="simpleClientHttpRequestFactory" class="org.springframework.http.client.SimpleClientHttpRequestFactory">
        <property name="readTimeout" value="60000"/>
        <property name="connectTimeout" value="5000"/>
    </bean>
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="simpleClientHttpRequestFactory"/>
        <property name="messageConverters">
            <list>
                <bean class=" com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
                <bean  class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

</beans>

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部