java后端上传下载文件

Wesley13
• 阅读 660

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 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**);
}

}

<**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**>

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
3年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这