用于上传文件的 Java 小程序

标签 java forms post applet

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

服务器上的 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();

最佳答案

这里有一些代码可能会对您有所帮助,它来 self 的一个旧项目,删除了一堆不相关的内容,请珍惜它的值(value)。基本上,我认为您问题中的代码缺少 HTTP 协议(protocol)所需的某些部分

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 小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1599018/

相关文章:

javascript - javascript中的隐藏表单文件POST

ruby-on-rails - rails 4 : Force method: :post

python - 在使用 ModelForm 创建的表单对象中设置用户字段

Node.js v8.11.1 尝试使用 https 模块 POST 时出现 EPROTO 错误

java - BFS 图遍历 - 将新节点追加到邻接矩阵

java - 如何在 JAXB xml 中隐藏 "null=' true'"

java - 奇怪的 java.lang.VerifyError

java - 如何将默认文件名设置为 Swing JFileChooser?

javascript - 让 Liferay 7 弹出窗口在底层表单中填充值

node.js - Google OAuth 使用刷新 token 获取新的访问 token