栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

后端调用文件上传接口upload上传文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

后端调用文件上传接口upload上传文件

一、问题起因

我在用Java的方式创建了文件,然后需要对其上传到文件服务器上去

二、问题展示

文件上传接口

 @PostMapping({"/upload"})
    public R upload(@RequestParam(value = "isdb",defaultValue = "false") boolean isdb, @RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RException("上传文件不能为空");
        } else {
        //省略具体实现
        }

    }

调用方式:

package com.dfec.project.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
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 java.io.*;

import static java.nio.charset.StandardCharsets.UTF_8;



public class UploadUtil {


    
    public static String doPostMulti(String url, String filePath, boolean isdb, String token) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.addBinaryBody("file", getBytesByFile(filePath), ContentType.DEFAULT_BINARY, filePath);
            builder.addTextBody("isdb", String.valueOf(isdb));
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            builder.setCharset(UTF_8);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            httpPost.addHeader("token", token);

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    
    public static byte[] getBytesByFile(String pathStr) {
        File file = new File(pathStr);
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

自己写main方法测试就可以了,这里虽然写的几行代码不多,但是可以学的知识点还是挺多的

 httpPost.setEntity(entity);

这行代码是来携带参数的,具体可以翻看下,他接受的是一个HttpEntity

这个是一个接口,具体的实现类有这些

有兴趣可以都了解测试下,时间有限,暂时不写太多的,后面有时间再详细写;

下面附上UrlEncodedFormEntity的调用方式

  
    public static String doPost(String url, Map params, String charset) {
        if (url.isEmpty()) {
            return null;
        }
        try {
            List pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList(params.size());
                for (Map.Entry entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNamevaluePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            CloseableHttpResponse response = HTTPCLIENT.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337244.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号