如何使用java提交表单中的文件?

时间:2011-11-24 21:48:21

标签: java file

我使用以下代码提交表单:

URL url = new URL(submit_url);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();

connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
connection.setRequestProperty("Cookie", cookie);            

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bw.write(query);
bw.write("\r\n");
bw.flush();
bw.close();

但我也需要提交一份文件。文件输入名称是:file,我的文件位于:d:/images/test.gif 请帮我提交图片。 查询是一个字符串:name = username& title = title

1 个答案:

答案 0 :(得分:0)

DataOutputStream创建HttpUrlConnection,然后将要上传的字节写入服务器:

DataOutputStream dataOutputStream = 
        new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(bytes);
dataOutputStream.close();