java Java小程序上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1599018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:13:52  来源:igfitidea点击:

Java applet to upload a file

javaformspostapplet

提问by user189352

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

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

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.

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

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

回答by Lauri Lehtinen

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

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

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

}

回答by brianegge

I'd suggest you take a look at Gallery Remote. This is an open source project for uploading photos to a PHP backend. It's a bit more full featured than what you may need, but you should be able to modify the code to your needs fairly easily.

我建议你看看Gallery Remote。这是一个用于将照片上传到 PHP 后端的开源项目。它的功能比您可能需要的要全面一些,但是您应该能够很容易地根据需要修改代码。

You could also look at JUpload. It's not as full featured, but it is open source and capable of the task.

你也可以看看JUpload。它的功能不是很全,但它是开源的并且能够胜任这项任务。