java HttpClients上传文件

硅谷探秘者 1916 0 0

服务端(接受文件)

	/**
	 * 上传文件接口
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/upFile",method = RequestMethod.POST)
	public AjaxResult upFile(@RequestParam("type")int type,@RequestParam("file")MultipartFile file) {
		
		System.out.println(type);
		String fileName=file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String phoName=UUID.randomUUID().toString()+suffix;
		/************************************************************************************/
		//图片处理开始
		if(file.isEmpty()){
            return AjaxResult.fail("请选择文件");
        }
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file.getInputStream());
            if(bi==null){
                return AjaxResult.fail("您上传的不是图片格式");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.fail("您上传的不是图片格式");
        }
        File path = new File(achievement_dir);//文件保存路径
        if(!path.exists()) {
            path.mkdirs();
        }
        File f=new File(path.getAbsolutePath(),phoName);
        try {
            file.transferTo(f);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("文件保存异常");
        }
        //图片处理结束
		/********************************************************************************************************/
		return AjaxResult.success("success");
	}

客户端(发送文件)

package com.dzqc.yx.img;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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;
/**
 * 测试
 * @author jiajia
 *
 */
public class TestMain {
	public static void main(String[] args) throws FileNotFoundException {
		String res=httpClientUploadFile(new File("D:\\test\\a.png"));
		System.out.println(res);
	}
	/**
     * @return 响应结果
     */
    public static String httpClientUploadFile(File file) {
        final String remote_url = "http://localhost:8095/signup/upFile";// 第三方服务器请求地址
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file",new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);//文件流
            builder.addTextBody("type","1");//普通字段
            
            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;
    }
}



评论区
请写下您的评论...
暂无评论...
猜你喜欢
minio 2263 创建buckets 创建serviceaccounts java maven依赖: dependency groupIdio.minio/groupId
前端(h5) 2743 后端这么写packagecn.com.dzqc.controller;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.sp
工具 2444 pom依赖dependencygroupIdcommons-net/groupIdartifactIdcommons-net/artifactIdversion3.6/version/dependencyFTP服务类packageclub.jiajiajia.bulider.service;importjava.io.IOException;importjava.io.InputStream;im
框架 2013 springboot与回显资源映射路径配置:packagecom.dzqc.yx.controller
框架 2757 $FileSizeLimitExceededException:Thefieldfileexceedsitsmaximumpermittedsizeof1048576bytes.yml加配置springboot2.0配置spring:servlet:multipart:max-file-s
框架 7712 一次实现的进度条原理:在之前,请求以下服务器,获取一个socketId(作用:用来标识本次连接,服务器端也是通过这个id找到对应的连接,然后给这个连接发送消息(进度)),此时socket
linux系统 1557 nginx代理报413(RequestEntityTooLarge)错误的解决方案RequestEntityTooLarge:请求的实体太大,nginx代理时默认的大小是1M解决方案:设置
java基础 981 核心类ZipOutputStream的api档请参考:https://nowjava.com/docs/java-api-11/java.base/java/util/zip
归档
2018-11  12 2018-12  33 2019-01  28 2019-02  28 2019-03  32 2019-04  27 2019-05  33 2019-06  6 2019-07  12 2019-08  12 2019-09  21 2019-10  8 2019-11  15 2019-12  25 2020-01  9 2020-02  5 2020-03  16 2020-04  4 2020-06  1 2020-07  7 2020-08  13 2020-09  9 2020-10  5 2020-12  3 2021-01  1 2021-02  5 2021-03  7 2021-04  4 2021-05  4 2021-06  1 2021-07  7 2021-08  2 2021-09  8 2021-10  9 2021-11  16 2021-12  14 2022-01  7 2022-05  1 2022-08  3 2022-09  2 2022-10  2 2022-12  5 2023-01  3 2023-02  1 2023-03  4 2023-04  2 2023-06  3 2023-07  4 2023-08  1 2023-10  1 2024-02  1 2024-03  1 2024-04  1
标签
算法基础 linux 前端 c++ 数据结构 框架 数据库 计算机基础 储备知识 java基础 ASM 其他 深入理解java虚拟机 nginx git 消息中间件 搜索 maven redis docker dubbo vue 导入导出 软件使用 idea插件 协议 无聊的知识 jenkins springboot mqtt协议 keepalived minio mysql ensp 网络基础 xxl-job rabbitmq haproxy srs 音视频 webrtc javascript
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。