Spring boot 文件上传与文件转发

 开发过程中应该离不开文件上传这一关的吧

       例如:  即时通讯和各种社交网站啊,为了让人关注到自己,也为了把自己更好的介绍给别人,头像上传

              :  财务系统  想到财务就想到了excel   整天和excel打交道的人   excel上传,批量数据等

             等等等等。。。

那么Spring boot里面怎么来实现文件上传呢?

               以及如果只是做文件上传的中转站而目标服务器是在其它地方呢,

 

这样:      

 需求总是千奇百怪,办法总是有很多种,这里就例举一种非常简单的就好

 

代码接上一章

这里就贴一下主要关键代码

新引入的包

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

 这里是文件转发的工具类

package com.example.demo.util;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
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.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;


public class HttpClientUtil {

    public static String httpClientUploadFile(String url,MultipartFile file) {
//        String remote_url = url;// 第三方服务器请求地址
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("type", "2");// 类似浏览器表单提交,对应input的name和value
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
public class ConfigBean {

    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        multipartResolver.setMaxUploadSize(104857600);
        multipartResolver.setMaxInMemorySize(40960);
        return multipartResolver;
    }
}
 @RequestMapping(value = "/uploadFile/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }
        String filename = UUID.randomUUID().toString();
        String suffix = "";
        String originalFilename = file.getOriginalFilename();
        // 截取文件的后缀名
        if (originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = filename + suffix;
        String filePath = "D:\\A\\B\\D\\";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
        }
        return "上传失败!";
    }

    @RequestMapping(value = "/uploadFile/uploadPermanent", method = RequestMethod.POST)
    @ResponseBody
    public String uploadPermanent(@RequestParam(value = "file") MultipartFile file) {
        String url = "http://192.168.1.56:9090";
        String ss= HttpClientUtil.httpClientUploadFile(url+"/uploadFile/upload",file);
        return ss;
    }

 

 如图就说明文件上传已经好了

 

 这里环绕了两次,一次是到中转方法上的,一个是到目标方法上,当然这里是把中转服务器和目标服务器写到了一起,但是场景是满足中转条件的

当然还有非常多的方法来帮助我们办到这些

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斗码士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值