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

后端调用文件上传接口upload上传文件,第1张

后端调用文件上传接口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;
    }

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4668405.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-06
下一篇 2022-11-06

发表评论

登录后才能评论

评论列表(0条)

保存