java 中的 MultipartEntity 类上传图片 在 php 中应该如何实现

java 中的MultipartEntity类上传图片 在php 中应该如何实现


    public static String sendHttpMessage(String url,Map<String, String> map, File file,String fileKey) throws Exception{
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        HttpPost post = null;
        try {
            if(StringUtil.isEmpty(url) || null == map || map.isEmpty()){
                return null;
            }
            //创建POST请求
            post = new HttpPost(url);
            post.setHeader("Server","nginx/1.14.2");
            MultipartEntity entity = new MultipartEntity();  
            //请求参数
            for(Entry<String,String> entry : map.entrySet()){
//                params.add(new BasicNameValuePair(key,map.get(key))); 
                entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));  
            }
            entity.addPart(fileKey,new FileBody(file));  
            post.setEntity(entity);  
            //发�?�请�?
             client = HttpClients.createDefault();
             response = client.execute(post);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
                throw new Exception("请求失败�?");
            }
            
            HttpEntity resEntity = response.getEntity();
            return null == resEntity ? "" : EntityUtils.toString(resEntity,CHARSET);
        }  catch (Exception e) {
            log.info("异常�?"+e);
            throw e;
        }
    finally {
         try{
             if(response != null){
                 response.close();
            }
             if(client != null){
                 client.close();
            }
             if (post != null) {
                post.releaseConnection();
            }
         } catch (IOException e) {
             log.error(e.getMessage(), e);
         }
        
    }
    }

MultipartEntity对象是servlet API3.0开始支持的,php有对应的文件上传技术。

一句话搞定:

move_uploaded_file($_FILES["file"]["tmp_name"],$filename);//将临时地址移动到指定地址
#$_FILES["file"]["tmp_name"]这个是二进制的文件流,后面那个是本地存储地址