JAVA Http 图片传输

话不多说,直接上代码

发送端:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
public class upLoadImg {    
    /**
     * 测试上传png图片
     *
     */
    public static void testUploadImage(){
         String url = "http://9ycegd4a.dongtaiyuming.net";
        String fileName = "C:\\HWKJ\\UploadImg\\test.jpg";
        Map<String, String> textMap = new HashMap<String, String>();
        //普通参数:可以设置多个input的name,value
/*        textMap.put("name", "testname");
        textMap.put("type", "2");*/
        //文件:设置file的name,路径
        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("file", fileName);
        String contentType = "";//image/png
         formUpload(url, textMap, fileMap,contentType);
    }
 
 
    /**
     * 上传图片
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @param contentType 没有传入文件类型默认采用application/octet-stream
     * contentType非空采用filename匹配默认的图片类型
     * @return 返回response数据
     */
    @SuppressWarnings("rawtypes")
    public static String formUpload(String urlStr, Map<String, String> textMap,
           Map<String, String> fileMap,String contentType) {
        System.out.println("开始发送");
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    System.out.println("传入名称:"+inputName);
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                    System.out.println(inputName+","+inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();
                    
                    //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默认的图片类型
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"; filename=\"" + filename
                            + "\"\r\n");
                    System.out.println(inputName+","+filename);
                    
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    DataInputStream in = new DataInputStream(
                            new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            System.out.println("响应数据:"+res);
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    
    public static void main(String[] args) {
        testUploadImage();
    }
}

Java接收端:

public FileResult upload(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) throws ParseException {

    System.out.println("您已进入图片上传服务");
    //获取文件在服务器的储存位置
    String path = "C:/workspace/img";
    File filePath = new File(path);
    System.out.println("文件的保存路径:" + path);
    if (!filePath.exists() && !filePath.isDirectory()) {
        System.out.println("目录不存在,创建目录:" + filePath);
        filePath.mkdir();
    }

    //获取原始文件名称(包含格式)
    String originalFileName = picture.getOriginalFilename();
    System.out.println("原始文件名称:" + originalFileName);

    //获取文件类型,以最后一个`.`为标识
    String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
    System.out.println("文件类型:" + type);
    //获取文件名称(不包含格式)
    String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
    DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date date = simpleDateFormat.parse("2020-04-28 02:33:29");

    long ts = date.getTime();

    System.out.println(ts);

    String res = String.valueOf(ts);  // 转化为字符串

    String fileName = res + name + "." + type;
    System.out.println("新文件名称:" + fileName);

    //在指定路径下创建一个文件
    File targetFile = new File(path, fileName);
    System.out.println("图片地址:"+path+"/"+fileName);
    //将文件保存到服务器指定位置
    try {
        picture.transferTo(targetFile);
        System.out.println("上传成功");
        //将文件在服务器的存储路径返回
        return new FileResult(true,fileName,path+"/"+fileName);
    } catch (IOException e) {
        System.out.println("上传失败");
        e.printStackTrace();
        return new FileResult(false, "上传失败","");
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要实现通过 HTTP 协议传输本地图片,你需要按照以下步骤进行操作: 1. 使用 Java 中的 File 类读取本地图片文件并转换为字节数组。 ```java File file = new File("path/to/image.jpg"); byte[] imageData = Files.readAllBytes(file.toPath()); ``` 2. 创建 HttpURLConnection 对象,并设置请求方法为 POST。 ```java URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); ``` 3. 设置请求头信息,包括 Content-Type 和文件名等。 ```java conn.setRequestProperty("Content-Type", "image/jpeg"); conn.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); ``` 4. 开启输出流并将字节数组写入到输出流中。 ```java conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(imageData); os.flush(); os.close(); ``` 5. 发送请求并获取响应结果。 ```java int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应结果 InputStream is = conn.getInputStream(); // ... } ``` 完整代码示例: ```java import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; public class HttpImageUploader { public static void main(String[] args) { try { // 读取本地图片文件并转换为字节数组 File file = new File("path/to/image.jpg"); byte[] imageData = Files.readAllBytes(file.toPath()); // 创建 HttpURLConnection 对象,并设置请求方法为 POST URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); // 设置请求头信息,包括 Content-Type 和文件名等 conn.setRequestProperty("Content-Type", "image/jpeg"); conn.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); // 开启输出流并将字节数组写入到输出流中 conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(imageData); os.flush(); os.close(); // 发送请求并获取响应结果 int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应结果 InputStream is = conn.getInputStream(); // ... } } catch (Exception e) { e.printStackTrace(); } } } ``` ### 回答2: 在Java中实现通过HTTP传输本地图片,可以通过以下步骤进行实现: 1. 使用Java的IO流读取本地图片文件,可以使用`FileInputStream`类来读取文件。首先,我们需要使用文件路径来创建一个`File`对象,然后使用`FileInputStream`来读取文件内容并保存到一个字节数组中。 2. 创建一个`URL`对象,指定要上传图片的目标URL地址。可以使用`URL`类的构造函数传入目标URL地址字符串来创建它。 3. 打开一个HTTP连接,可以使用`URLConnection`类的`openConnection()`方法打开一个连接,并强制转换为`HttpURLConnection`对象,因为HTTP传输需要使用这个对象来设置请求方法、请求头等。 4. 设置HTTP连接的请求方法为POST,并设置一些必要的请求头信息。例如,可以将请求头字段"Content-Type"设置为"multipart/form-data",表示传输的内容是多部分的。 5. 创建一个输出流,将字节数组作为请求体发送给目标URL。可以使用`HttpURLConnection`对象的`getOutputStream()`方法获取输出流,并使用`write()`方法写入字节数组。 6. 获取服务器响应,可以使用`HttpURLConnection`对象的`getInputStream()`方法获取服务器响应的输入流,然后读取响应内容。 7. 最后,记得关闭输入流和输出流,并断开HTTP连接。 总结起来,通过以上步骤,我们可以实现通过HTTP传输本地图片。需要注意的是,为了避免出现内存泄漏和资源未释放的情况,应该适时地关闭输入流和输出流,并及时断开HTTP连接。 ### 回答3: 要使用Java实现通过HTTP传输本地图片,可以按照以下步骤进行: 1. 首先,需要使用Java的文件输入流将本地的图片文件读取到内存中。可以使用`FileInputStream`类来实现,将文件路径作为参数传递给该类的构造函数。 ```java FileInputStream fileInputStream = new FileInputStream("图片文件路径"); ``` 2. 接下来,需要创建一个URL对象,指定HTTP的目标地址。可以使用`URL`类来实现,将目标地址作为参数传递给该类的构造函数。 ```java URL url = new URL("HTTP目标地址"); ``` 3. 然后,需要创建一个HTTP连接对象,可以使用`HttpURLConnection`类来实现。通过调用`openConnection()`方法创建该对象,并将URL对象作为参数传递给该方法。 ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); ``` 4. 设置HTTP请求方法为POST,并启用输出流和输入流。设置请求头的Content-Type为multipart/form-data,以支持文件上传。同时设置连接超时和读取超时的时间。 ```java connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----Boundary"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); ``` 5. 获取输出流对象,并将图片数据写入输出流。 ```java OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } ``` 6. 获取服务器返回的输入流,并对其进行相应的处理。 ```java InputStream inputStream = connection.getInputStream(); // 对返回的数据进行处理 ``` 7. 最后,关闭输入流、输出流和连接。 ```java fileInputStream.close(); outputStream.close(); connection.disconnect(); ``` 以上就是通过Java实现HTTP传输本地图片的基本步骤。根据具体的需求,还可以添加其他功能,比如设置请求头中的其他参数、添加身份验证等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值