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


/**
 * @program: rf-project
 * @description:
 * @author: trg
 * @create: 2021-10-18 15:28
 */
public class UploadUtil {


    /**
     * 该方法为调用OSS上传文件的方法
     *
     * @param url      服务部署地址
     * @param filePath 文件路径
     * @param isdb     是否进行数据库存储 false:不存储
     * @param token    token令牌
     * @return
     */
    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;
    }

    /**
     * 将文件转换为byte数组
     *
     * @param pathStr
     * @return
     */
    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

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

后端调用文件上传接口upload上传文件_第1张图片

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

下面附上UrlEncodedFormEntity的调用方式

  /**
     * HTTP Post 获取内容
     *
     * @param url     请求的url地址
     * @param params  请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    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;
    }

 

你可能感兴趣的:(java,java)