Java小程序上传文件 [英] Java applet to upload a file

查看:168
本文介绍了Java小程序上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个Java小程序读取客户机的文件,并创造了PHP服务器上载POST请求。

在服务器上的PHP脚本应接受的形式文件作为普通文件上传提交。
我使用下面的code。文件内容传递给PHP脚本
但它们不正确地转换成图像。

  //的uploadURL将PHP脚本像一个网址
// http://www.example.com/uploadfile.php网址URL =新的URL(的uploadURL);
HttpURLConnection的CON =(HttpURLConnection类)url.openConnection();
con.setRequestMethod(POST);
con.setDoInput(真);
con.setDoOutput(真);InputStream为=新的FileInputStream(C://img.jpg);
OutputStream的OS = con.getOutputStream();
字节[] = B1新的字节[千万]
INT N;
而((N = is.​​read(B1))!= - 1){
os.write(你好,0,5);
测试+ = B1;}
con.connect();


解决方案

下面是一些code,可以帮助你,那是从我的旧项目,去掉一堆不相关的东西之一,把它用于它的价值。基本上,我认为你的问题code缺少一些零件HTTP协议要求

 公共类UploaderExample
{
    私有静态最后弦乐边界=--7d021a37605f0;    公共无效上传(URL网址,列表与LT;文件>文件)抛出异常
    {
        HttpURLConnection的theUrlConnection =(HttpURLConnection类)url.openConnection();
        theUrlConnection.setDoOutput(真);
        theUrlConnection.setDoInput(真);
        theUrlConnection.setUseCaches(假);
        theUrlConnection.setChunkedStreamingMode(1024);        theUrlConnection.setRequestProperty(内容类型,的multipart / form-data的;边界=
                +边界);        DataOutputStream类httpOut =新的DataOutputStream类(theUrlConnection.getOutputStream());        的for(int i = 0; I< files.size();我++)
        {
            文件f = files.get(ⅰ);
            字符串str = - +边界+\\ r \\ n
                       +内容处置:表格数据;名称= \\文件+ I +\\;文件名= \\+ f.getName()+\\\\ r \\ n
                       +内容类型:图像/ PNG \\ r \\ n
                       +\\ r \\ n;            httpOut.write(str.getBytes());            的FileInputStream uploadFileReader =新的FileInputStream(F);
            INT numBytesToRead = 1024;
            INT availableBytesToRead;
            而((availableBytesToRead = uploadFileReader.available())大于0)
            {
                字节[] bufferBytesRead;
                bufferBytesRead = availableBytesToRead> = numBytesToRead?新的字节[numBytesToRead]
                        :新的字节[availableBytesToRead]
                uploadFileReader.read(bufferBytesRead);
                httpOut.write(bufferBytesRead);
                httpOut.flush();
            }
            httpOut.write(( - +边界+ - \\ r \\ n)的getBytes());        }        httpOut.write(( - +边界+ - \\ r \\ n)的getBytes());        httpOut.flush();
        httpOut.close();        //读取和放大器;解析响应
        InputStream为= theUrlConnection.getInputStream();
        StringBuilder的响应=新的StringBuilder();
        字节[] = respBuffer新的字节[4096];
        而(is.read(respBuffer)GT; = 0)
        {
            response.append(新的String(respBuffer).trim());
        }
        is.close();
        的System.out.println(response.toString());
    }    公共静态无效的主要(字串[] args)抛出异常
    {
        清单<文件>名单=新的ArrayList<文件>();
        list.add(新文件(C:\\\\ square.png));
        list.add(新文件(C:\\\\ narrow.png));
        UploaderExample上传=新UploaderExample();
        uploader.upload(新URL(http://systemout.com/upload.php),清单);
    }}

I am looking for a Java applet to read a file from client machine and creat a POST request for PHP server uploading.

PHP script on server should receive the file as normal file upload in FORM submit. I am using the following code. The file contents are passed to PHP script but they are not correctly converted to an image.

//uploadURL will be a url of PHP script like
// http://www.example.com/uploadfile.php

URL url = new URL(uploadURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);

InputStream is = new FileInputStream("C://img.jpg");
OutputStream os = con.getOutputStream();
byte[] b1 = new byte[10000000];
int n;
while((n = is.read(b1)) != -1) {
os.write("hello" , 0, 5);
test += b1;

}
con.connect();

解决方案

Here is some code that might help you it's from one of my old projects with a bunch of unrelated stuff removed, take it for what it's worth. Basically, I think the code in your question is missing some parts that the HTTP protocol requires

public class UploaderExample
{
    private static final String Boundary = "--7d021a37605f0";

    public void upload(URL url, List<File> files) throws Exception
    {
        HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
        theUrlConnection.setDoOutput(true);
        theUrlConnection.setDoInput(true);
        theUrlConnection.setUseCaches(false);
        theUrlConnection.setChunkedStreamingMode(1024);

        theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                + Boundary);

        DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());

        for (int i = 0; i < files.size(); i++)
        {
            File f = files.get(i);
            String str = "--" + Boundary + "\r\n"
                       + "Content-Disposition: form-data;name=\"file" + i + "\"; filename=\"" + f.getName() + "\"\r\n"
                       + "Content-Type: image/png\r\n"
                       + "\r\n";

            httpOut.write(str.getBytes());

            FileInputStream uploadFileReader = new FileInputStream(f);
            int numBytesToRead = 1024;
            int availableBytesToRead;
            while ((availableBytesToRead = uploadFileReader.available()) > 0)
            {
                byte[] bufferBytesRead;
                bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
                        : new byte[availableBytesToRead];
                uploadFileReader.read(bufferBytesRead);
                httpOut.write(bufferBytesRead);
                httpOut.flush();
            }
            httpOut.write(("--" + Boundary + "--\r\n").getBytes());

        }

        httpOut.write(("--" + Boundary + "--\r\n").getBytes());

        httpOut.flush();
        httpOut.close();

        // read & parse the response
        InputStream is = theUrlConnection.getInputStream();
        StringBuilder response = new StringBuilder();
        byte[] respBuffer = new byte[4096];
        while (is.read(respBuffer) >= 0)
        {
            response.append(new String(respBuffer).trim());
        }
        is.close();
        System.out.println(response.toString());
    }

    public static void main(String[] args) throws Exception
    {
        List<File> list = new ArrayList<File>();
        list.add(new File("C:\\square.png"));
        list.add(new File("C:\\narrow.png"));
        UploaderExample uploader = new UploaderExample();
        uploader.upload(new URL("http://systemout.com/upload.php"), list);
    }

}

这篇关于Java小程序上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆