下载网络文件上传到FS

发布时间 2023-07-24 11:27:11作者: 漫步CODE人生
package com.tianwen.springcloud.microservice.base.service.book;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianwen.springcloud.commonapi.base.entity.FileResponse;
import com.tianwen.springcloud.commonapi.base.response.Response;
import com.tianwen.springcloud.datasource.base.BaseService;
import com.tianwen.springcloud.microservice.base.dao.book.BookTransferMapper;
import com.tianwen.springcloud.microservice.base.entity.book.BookTransfer;
import com.tianwen.springcloud.microservice.base.request.BookTransferReq;
import com.tianwen.springcloud.microservice.base.service.content.MajorContentService;

import tk.mybatis.mapper.entity.Example;

@Service
public class BookTransferService extends BaseService<BookTransfer> 
{

    @Resource
    DiscoveryClient discoveryClient;


    public BookTransfer getBookInfoById(String tenantId, String bookId)
    {
        BookTransfer book = selectByKey(bookId);

        // 封面图片上传到FS转换
        if(null != book.getCover())
        {
            String[] coverUrls = book.getCover().split(",");
            String dirPath = "/tmp/thirdbookcover/";
            for(int i=0; i<coverUrls.length; i++)
            {
                if(coverUrls[i].startsWith("http"))
                {
                    String fileName = coverUrls[i].substring(coverUrls[i].lastIndexOf("/") + 1);
                    
                    try
                    {
                        // 先下载到服务器,然后上传到FS
                        downloadHttpUrl(coverUrls[i], dirPath, fileName);
                        String filePath = dirPath + fileName;
                        File file = new File(filePath);
                        if(file.exists())
                        {
                            List<FileSystemResource> fileSsytemResourceList = new ArrayList<FileSystemResource>();
                            
                            fileSsytemResourceList.add(new FileSystemResource(filePath));
                            
                            FileResponse fileResponse = getFileResponse(tenantId, fileSsytemResourceList);
                            if(null != fileResponse && 
                                    null != fileResponse.getFileInfos() && 
                                    fileResponse.getFileInfos().size() > 0 &&
                                    null != fileResponse.getFileInfos().get(0).getLocalPath())
                            {
                                coverUrls[i] = fileResponse.getFileInfos().get(0).getLocalPath();
                            }
                            
                            String newCover = Arrays.toString(coverUrls);
                            book.setCover(newCover);
                            updateByPrimaryKey(book);
                        }
                    } 
                    catch (Exception e) 
                    {
                        logger.error("上传FS异常:", e);
                        e.printStackTrace();
                    }
                }
            }
        }
        
        book = transferBookInfo(book);
        
        return book;
    }
    
    /** 
     * 下载文件---返回下载后的文件存储路径 
     *  
     * @param url 文件地址 
     * @param dir 存储目录 
     * @param fileName 存储文件名 
     * @return 
     */  
    public void downloadHttpUrl(String url, String dir, String fileName) 
    {  
        try 
        {  
            URL httpurl = new URL(url);  
            File dirfile = new File(dir);    
            if (!dirfile.exists()) 
            {    
                dirfile.mkdirs();  
            }  
            FileUtils.copyURLToFile(httpurl, new File(dir+fileName));  
        } 
        catch (Exception e) 
        {  
            logger.error("下载文件 downloadHttpUrl异常:", e);
            e.printStackTrace();  
        }  
    }  
    
    public FileResponse getFileResponse(String tenantId, List<FileSystemResource> resourceList)
        throws Exception
    {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
        HttpHeaders post = new HttpHeaders();
        post.add("user-agent", "Mozillll" + "a/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)");
        post.add("content-Type", "multipart/form-data;charset=UTF-8");
        post.add("Host", "****");
        post.add("Accept-Encoding", "gzip");
        post.add("charset", "utf-8");
        post.add("branchCode", tenantId);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        for (int i = 0; i < resourceList.size(); i++)
        {
            param.add("file" + i, resourceList.get(i));
        }
        
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, post);
        Optional<String> optionalUrl = this.resolveUrl("http://fs/fs/fs/file/upload", "FS");
        if (optionalUrl.isPresent())
        {
            try
            {
                return restTemplate.postForObject(optionalUrl.get(), requestEntity, FileResponse.class);
            }
            catch (Exception e)
            {
                logger.error("上传FS异常:" + optionalUrl.get(), e);
                throw new Exception("上传FS异常:" + optionalUrl.get(), e);
            }
        }
        else
        {
            throw new Exception("上传地址不可用");
        }
    }

    public Optional<String> resolveUrl(String hs, String instance)
    {
        try
        {
            URI uri = new URI(hs);
            final List<ServiceInstance> instances = discoveryClient.getInstances(instance);
            if (null != instances && instances.size() > 0)
            {
                Collections.shuffle(instances);
                ServiceInstance serviceInstance = instances.get(0);
                return Optional.of(new URI(uri.getScheme(), null, serviceInstance.getHost(), serviceInstance.getPort(),
                    uri.getPath(), uri.getQuery(), null).toString());
            }
        }
        catch (URISyntaxException e)
        {
            logger.error("resolveUrl 异常: " + hs, e);
        }

        return Optional.empty();
    }


}