gpt4 book ai didi

java - 使用 httpurlconnection multipart/form-data 上传数组列表

转载 作者:行者123 更新时间:2023-12-01 09:07:03 29 4
gpt4 key购买 nike

我需要上传Arraylist无需使用任何库即可将图像发送到服务器。我正在使用 Asynctask上传单个图像,它在 httpurlconnection multipart/form-data 的帮助下完美运行。现在我需要更改我的代码以使用 Arraylist<String> 上传任何类型的多个文件但我的问题是现有代码的 FileinputStream不支持arraylist,我不知道用什么代替Fileinputstream将arraylist上传到服务器,我也不想为此使用任何库。

public class multipart_test extends AsyncTask<Void,Void,String> {
Context context;
String Images;
public static final String TAG = "###Image Uploading###";


public multipart_test(Context context,String Upload_Images) {
this.context = context;
this.Images = Upload_Images;

}

@Override
protected String doInBackground(Void... params) {
BufferedReader reader;
String WebPath = null;
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
//todo change URL as per client ( MOST IMPORTANT )
URL url = new URL("10.0.0.1/uploadMultipart.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Allow Inputs &amp; Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
FileInputStream fileInputStream;
DataOutputStream outputStream;
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);

outputStream.writeBytes("Content-Disposition: form-data; name=\"reference\""+ lineEnd);
outputStream.writeBytes(lineEnd);
//outputStream.writeBytes("my_refrence_text");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);

outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadFile\";filename=\"" + "profileImage" +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);

//Dummy ArrayList for upload
ArrayList<String> uploadFiles = new ArrayList<>();
uploadFiles.add(Images);
uploadFiles.add(Images);
uploadFiles.add(Images);
uploadFiles.add(Images);


fileInputStream = new FileInputStream(uploadFiles); // NOT SUPPORTING ARRAYLIST HERE
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
}
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String result = null;
if (serverResponseCode == 200) {
StringBuilder s_buffer = new StringBuilder();
InputStream is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = br.readLine()) != null) {
s_buffer.append(inputLine);
}
result = s_buffer.toString();
}
connection.getInputStream().close();
outputStream.flush();
outputStream.close();
if (result != null) {
Log.d("result_for upload", result);
}
return WebPath;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


}

我也试着把 FileInputStream进入循环,但将图像上传到多个请求不是我想要的。我的服务器要求应用程序对 n 个图像发出单个请求。任何帮助将不胜感激,但不使用任何库

最佳答案

请注意,如果此代码确实适用于 HttpURLConnection,我还没有尝试过,但它应该。

根据我从互联网上读到的内容,您仍然可以使用您提到的那个循环,但需要进行一些修改。

我在这里遵循了关于 multipart/form-data 的教程 dev.to ,为了让这篇文章更像是一篇学习文章,我会告诉你这个方法应该发生什么。

multipart/form-data 是这样发送的

--boundary
Content-Disposition: form-data; name="something1"

data1
--boundary
Content-Disposition: form-data; name="something2"

data2
--boundary--

我要做的是创建一个新方法,但您可以在现有方法中编写代码。
public byte[] get_multipart_data(List<String> files, String boundary)

您要写的是边界,然后是处置,然后是数据。对所有文件执行此操作,然后发送关闭边界。这将生成您想要的 multipart/form-data 结构。

在伪代码中,这将是
loop for all files
write "--boundary"
write "Content-Disposition: ...."
write image_data
end
write "--boundary--"

代码可以这样写,首先你定义你的变量
ByteArrayOutputStream message = null;
DataOutputStream stream = null;

FileInputStream fileInputStream;

int maxBufferSize = 1024 * 1024;
byte[] buffer = new byte[maxBufferSize];
byte[] sendData = new byte[0];

这里是生成数据的地方。
它从连接边界开始,然后读取数据。该数据被写入流中,然后您继续循环所有文件/图像。
try {
message = new ByteArrayOutputStream();
stream = new DataOutputStream(message);

// Loop though all file names
for(String fileName : files) {
stream.writeBytes("--" + boundary + "\r\n"); // Start boundary
stream.writeBytes("Content-Disposition: form-data; name=\"" + fileName + "\"\r\n\r\n");

// Read the image data
fileInputStream = new FileInputStream(fileName);
int readBytes = 0;
while((readBytes = fileInputStream.read(buffer)) != -1) {
// Write file data to output
stream.write(buffer, 0, readBytes);
}
fileInputStream.close();

stream.writeBytes("\r\n");
}
stream.writeBytes("--" + boundary + "--\r\n"); // Closing boundary

sendData = message.toByteArray();
} catch(IOException e) {
e.printStackTrace();
}

现在字节数组 sendData将包含您需要与 HttpURLConnection 一起发送的 multipart/form-data。

我已经很久没有在这里那么活跃了。告诉我您是否需要更多规范或我澄清我的文字:D

关于java - 使用 httpurlconnection multipart/form-data 上传数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638941/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com