Java教程

java中用post方式传输某个文件

本文主要是介绍java中用post方式传输某个文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文章目录

    • 方式一:直接取本地某个文件进行上传
    • 方式二:接收base64格式然后转成文件进行上传

方式一:直接取本地某个文件进行上传

package com.picc.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 com.newtouch.log.Ulog;

public class UpImageUtil {
	public static void main(String[] args) {
	    // 取本地文件
		File file = new File("/Users/wuxing/Desktop/test.png");
		// 创建httpPost
		HttpPost httpPost = new HttpPost("http://10.100.100.100/XXXXXXXXX");
		Map<String, String> header = new HashMap<String, String>();

		header.put("organ_id", "111");
		for (String key : header.keySet()) {
			httpPost.setHeader(key, header.get(key));
		}
		try {
			// 设置参数
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			multipartEntityBuilder.addBinaryBody("file", file);
			HttpEntity reqEntity = multipartEntityBuilder.build();
			httpPost.setEntity(reqEntity);
		} catch (Exception e) {
			Ulog.error(e);
		}
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			// 执行请求
			response = httpClient.execute(httpPost);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			Ulog.error(e);
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				Ulog.error(e);
			}
		}
		System.out.println(responseContent);

	}
}


方式二:接收base64格式然后转成文件进行上传

public  Map<String,String> uploadPictureImageToETong(Map<String,String> map) {

        BaseResult  baseResult = new BaseResult();
        String policyUuid = map.get("policyUuid");
        String base64Image = map.get("base64Image");
        String imageType = map.get("imageType");
        String imageUrl = map.get("imageUrl");
        String organId = map.get("organId");
 

        OutputStream out = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        Map<String,String> resultMap = new HashMap<>();

        try {
            String dataPrix = "";
            String [] d = base64Image.split("base64,");
            if(d != null && d.length == 2){
                dataPrix = d[0];
                // data = d[1];
            }else{
                throw new Exception("图片上传失败,影像数据格式不合法");
            }

            //前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
            base64Image = base64Image.replaceAll(" ", "+");


            //图片后缀
            String suffix = "";
            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//data:image/jpeg;base64,base64编码的jpeg图片数据
                suffix = ".jpeg";
                //去除base64中无用的部分,上传相应的图片的是去掉对应的即可
                base64Image = base64Image.replace("data:image/jpeg;base64,", "");
            } else if("data:image/jpg;".equalsIgnoreCase(dataPrix)){//data:image/gif;base64,base64编码的jpg图片数据
                suffix = ".jpg";
                base64Image = base64Image.replace("data:image/jpg;base64,", "");
            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//data:image/png;base64,base64编码的png图片数据
                suffix = ".png";
                base64Image = base64Image.replace("data:image/png;base64,", "");
            }else {
                //throw new Exception("上传图片格式不合法");
                String[] base64BankCarkImageString = base64Image.split(",");
                base64Image = base64BankCarkImageString[1];
                suffix = ".png";
            }

            // 生成文件名
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String strDateName = dateFormat.format(new Date());
            String strTypeName;
            
            switch (imageType){
                case "1":
                    strTypeName = "bankOn";
                    break;
                case "2":
                    strTypeName = "bankDown";
                    break;
                case "3":
                    strTypeName = "signHead";
                    break;
                case "4":
                    strTypeName = "signHand";
                    break;
                default:
                    strTypeName = "image";
                    break;
            }
            //上传文件的名字
            String strFileName = strDateName + strTypeName + suffix;


            BASE64Decoder base64decoder = new BASE64Decoder();
            //base64图片解码
            byte[] byteimgDate = base64decoder.decodeBuffer(base64Image);

            for (int i = 0; i < byteimgDate.length; ++i) {
                // 调整异常数据
                if (byteimgDate[i] < 0) {
                    byteimgDate[i] += 256;
                }
            }

            //上传图片路径
            File imgFile = new File(strFileName);
            imgFile.createNewFile();

            if (!imgFile.exists()) {
                imgFile.createNewFile();
            }

            out = new FileOutputStream(strFileName);
            out.write(byteimgDate);
            out.flush();
            out.close();

            // 创建httpPost
            HttpPost httpPost = new HttpPost(imageUrl);
            Map<String, String> header = new HashMap<String, String>();
            //设置机构代码
            header.put("organ_id", organId);
            for (String key : header.keySet()) {
                httpPost.setHeader(key, header.get(key));
            }

            // 设置参数
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody("file", imgFile);
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httpPost.setEntity(reqEntity);

            // 创建默认的httpClient实例.
            httpClient = HttpClients.createDefault();
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");

            HolderBankInfoSubmitResponseDTO submitResponse = new HolderBankInfoSubmitResponseDTO();
            if (StringUtils.isNotBlank(responseContent)) {
                submitResponse = JSONObject.parseObject(responseContent, HolderBankInfoSubmitResponseDTO.class);
            }
    
            if (submitResponse == null) {
                baseResult.setRet(BaseResult.SYS_ERROR);
                baseResult.setMsg("上传接口返回为空");
                baseResult.validate();
            }
            if("success".equals(submitResponse.getFlag())){
                resultMap.put("fileNo",submitResponse.getDefmap().getFileNo());
            }else{
    
                baseResult.setRet(BaseResult.SYS_ERROR);
                baseResult.setMsg(submitResponse.getMsg().toString());
                baseResult.validate();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return resultMap;
    }

```
这篇关于java中用post方式传输某个文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!