HttpURLConnection上传文件(图片)小试

需求:用HttpURLConnection模拟上传图片并把图片的名称也要传递过去.

简单分析:写入流的时候依次写入 图片名称 + "|" 分隔符 +  图片流

然后服务器接收的再处理流.分别取出图片名和图片.

/** */ /**
     * 上传方法
     * 返回上传完毕的文件名
     * *
     
*/

    
public  String upload(File f)
    
{
        
try
        
{
            
//服务器IP(这里是从属性文件中读取出来的)
            String hostip = FileSupport.getServerIP();
            URL url 
= new URL("http://"+ hostip +"/oxServer/ReceiveServlet");
            
            HttpURLConnection uc 
= (HttpURLConnection) url.openConnection();
            
//上传图片的一些参数设置
            uc
                    .setRequestProperty(
                            
"Accept",
                            
"image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
            uc.setRequestProperty(
"Accept-Language""zh-cn");
            uc
                    .setRequestProperty(
"Content-type",
                            
"multipart/form-data;   boundary=---------------------------7d318fd100112");
            uc.setRequestProperty(
"Accept-Encoding""gzip,   deflate");
            uc
                    .setRequestProperty(
"User-Agent",
                            
"Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
            uc.setRequestProperty(
"Connection""Keep-Alive");
            uc.setDoOutput(
true);
            uc.setUseCaches(
true);
        
            
//读取文件流
            int size = (int) f.length();
            
byte[] data = new byte[size];
            FileInputStream fis 
= new FileInputStream(f);
            OutputStream out 
= uc.getOutputStream();
            fis.read(data, 
0, size);
            
//写入文件名
            out.write(f.getName().trim().getBytes());
            
//写入分隔符
            out.write('|');
            
//写入图片流
            out.write(data);
            out.flush();
            out.close();
            fis.close();
            
            
//读取响应数据
            int code = uc.getResponseCode();
            String sCurrentLine 
= "";
            
//存放响应结果
            String sTotalString = "";
            
if (code == 200)
            
{
                java.io.InputStream is 
= uc.getInputStream();
                BufferedReader reader 
= new BufferedReader(
                        
new InputStreamReader(is));
                
while ((sCurrentLine = reader.readLine()) != null)
                    
if (sCurrentLine.length() > 0)
                        sTotalString 
= sTotalString + sCurrentLine.trim();
            }

            
else
            
{
                sTotalString 
= "远程服务器连接失败,错误代码:" + code;
            }

            
return sTotalString;
        }

        
catch (Exception e)
        
{
            e.printStackTrace();
        }

        
return null;
    }


服务器Servlet:
public   void  doGet(HttpServletRequest request, HttpServletResponse response)
            
throws  ServletException, IOException
    
{
        ServletInputStream inStream 
= request.getInputStream(); // 取HTTP请求流
        int size = request.getContentLength(); // 取HTTP请求流长度

        
byte[] buffer = new byte[size]; // 用于缓存每次读取的数据
        byte[] result = new byte[size]; // 用于存放结果的数组
        int count = 0;
        
int rbyte = 0;
        
// 循环读取
        while (count < size)
        
{
            rbyte 
= inStream.read(buffer); // 每次实际读取长度存于rbyte中 sflj
            for (int i = 0; i < rbyte; i++)
            
{
                result[count 
+ i] = buffer[i];
            }

            count 
+= rbyte;
        }


        
// 先找到文件名和图片流的标志位'|'
        int index = 0;
        
for (int i = 0; i < result.length; i++)
        
{
            
byte b = result[i];
            
if (b == '|')
            
{
                index 
= i;
                
break;
            }

        }


        
// 存放文件名
        byte name[] = new byte[index + 1];
        
// 存放图片字节
        byte[] img = new byte[size - index];
        
for (int i = 0; i < result.length; i++)
        
{
            
if (i < index)
            
{
                name[i] 
= result[i];
            }

            
if (i > index)
            
{
                
// 这时注意img数组的index要从0开始
                img[i - index - 1= result[i];
            }

        }

        
// 还原文件名
        String fileName = new String(name);

        inStream.close();

        String newFileName 
= renameFile(fileName);
        
// 响应客户端
        response.setContentType("text/html");
        
// 注意响应中文数据时要设置
        response.setCharacterEncoding("GBK");
        PrintWriter out 
= response.getWriter();
        
//可能情况 0 数据库无相关记录 1 文件名不符合要求 其它情况为正常
        if(newFileName.equals("0"))
        
{
            out.write(
"0|" + fileName);
        }

        
else if(newFileName.equals("1"))
        
{
            out.write(
"1|" + fileName);
        }

        
else
        
{
            out.write(fileName);
        }

        out.close();
        
//上传错误中止后续操作
        if(newFileName.length()<= 1)
        
{
            
return;
        }

        
        File f 
= new File(ImageSupport.getOriginal() + "/" + newFileName);
        FileOutputStream fos 
= new FileOutputStream(f);
        fos.write(img);
        fos.flush();
        fos.close();
        
// 改变图片大小后重新放置到新地点
        ImageSupport.changeImageSize(f, ImageSupport.getAfter() + "/"
                
+ newFileName, 300300);
    }


我写的是一个批量上传图片的程序,经测试通过.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: HttpURLConnection可以用来上传文件,具体步骤如下: 1. 创建一个URL对象,指定上传文件的地址。 2. 打开连接,使用HttpURLConnection的openConnection()方法。 3. 设置请求方法为POST,使用setRequestMethod()方法。 4. 设置请求头,包括Content-Type和Content-Length,使用setRequestProperty()方法。 5. 开启输出流,使用setDoOutput(true)方法。 6. 创建一个输出流,将文件写入输出流。 7. 关闭输出流。 8. 获取响应码,使用getResponseCode()方法。 9. 关闭连接。 示例代码如下: ``` URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZugW"); conn.setRequestProperty("Content-Length", String.valueOf(file.length())); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); Files.copy(file.toPath(), os); os.close(); int responseCode = conn.getResponseCode(); conn.disconnect(); ``` 其中,file为要上传的文件对象。在设置Content-Type时,需要指定boundary,这是一个分隔符,用于分隔不同的表单字段。在这个例子中,使用了WebKitFormBoundary7MA4YWxkTrZugW作为boundary。在写入文件时,使用了Java 7中的Files.copy()方法,将文件内容写入输出流。最后,获取响应码并关闭连接。 ### 回答2: httpurlconnection是一个用于进行HTTP连接的类,通过它我们可以实现上传文件的功能。 首先,我们需要创建一个httpurlconnection对象,可以通过url.openConnection()方法进行创建。 其次,我们需要设置http请求方法为POST,以便我们能够将文件上传到服务器。可以通过setRequestMethod("POST")方法进行设置。 然后,我们需要设置http请求头信息,包括Content-Type,Content-Length等信息。可以通过setRequestProperty()方法进行设置。 接下来,我们需要使用httpurlconnection实例的输出流将文件上传到服务器。可以通过getOutputStream()方法获取输出流,将文件写入输出流中,实现上传文件的功能。 最后,我们需要获取http响应信息,以便判断文件是否上传成功。可以使用httpurlconnection实例的getResponseCode()方法获取http响应码,通常200表示上传成功。 总之,httpurlconnection上传文件功能的实现可以分为以下几个步骤: 1. 创建httpurlconnection对象; 2. 设置http请求方法为POST; 3. 设置http请求头信息; 4. 获取输出流并将文件上传到服务器; 5. 获取http响应信息并判断上传结果。 需要注意的是,在进行文件上传时需要注意文件大小以及文件传输速度等问题,以免影响服务器的运行。 ### 回答3: HttpURLConnectionJava中处理HTTP请求最常用的类之一。利用HttpURLConnection可以完成上传文件的功能。 上传文件的过程有以下几个步骤: 1. 打开连接:在HttpURLConnection中,我们可以使用URL.openConnection()方法来建立连接。在这之前,需要先构造一个URL对象,将要上传的文件的地址作为URL的参数。 2. 设置请求头:在上传文件时,需要设置一些请求头信息,以告诉服务器文件的类型、文件名等信息。设置请求头可以使用HttpURLConnection.setRequestProperty()方法来完成。 3. 打开输出流:在上传文件时,需要将文件数据发送给服务器,需要向服务器写入数据。可以使用HttpURLConnection.getOutputStream()方法获得一个输出流,通过输出流将文件数据发送给服务器。 4. 读取服务器返回的响应码:在开始上传文件前,可以发起一个HEAD请求(使用setRequestMethod("HEAD")方法),检查服务器是否支持上传文件,以及服务器是否可以接收此类型的文件。在上传文件完成后,服务器会返回一个响应码。可以使用HttpURLConnection.getResponseCode()方法来获得服务器返回的响应码。 5. 关闭连接:在完成所有操作后,需要关闭连接,释放相关资源。可以使用HttpURLConnection.disconnect()方法来关闭连接。 示例代码如下: ```java String urlStr = "http://example.com/upload"; // 构造URL对象 URL url = new URL(urlStr); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求头 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----boundary"); // 允许输出数据 conn.setDoOutput(true); // 打开输出流 DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream()); // 将文件数据写入输出流 File file = new File("C:/example.jpg"); InputStream inputStream = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; inputStream.read(data); outputStream.write(data); // 关闭输入输出流 inputStream.close(); outputStream.close(); // 获取服务器返回的响应码 int code = conn.getResponseCode(); // 关闭连接 conn.disconnect(); ``` 需要注意的是:当上传文件时,需要通过multipart/form-data格式来提交,其中boundary是一个随机的字符串,用于分隔不同的表单数据。而且,需要对文件数据进行编码,以确保文件数据可以正确传输。在Java中,可以使用DataOutputStream类进行数据编码和传输。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值