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

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

问题描述

我正在寻找一个 Java 小程序来从客户端机器读取文件并为 PHP 服务器上传创建一个 POST 请求.

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

服务器上的 PHP 脚本应该像在 FORM 提交中的正常文件上传一样接收文件.我正在使用以下代码.文件内容传递给 PHP 脚本但它们没有正确转换为图像.

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();

推荐答案

这里有一些代码可能会对您有所帮助.它来自我的一个旧项目,删除了一堆不相关的东西,物有所值.基本上,我认为您问题中的代码缺少 HTTP 协议所需的某些部分

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天全站免登陆