Java implements the method of segmenting a file and uploading it over HTTP

  • 2020-04-01 03:59:59
  • OfStack

This article illustrates a Java method for segmenting files and uploading them over HTTP. Share with you for your reference. The details are as follows:

1. First, segment the file, using RandomAccessFile
2. Upload the separated content to HTTP after segmentation


URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.setRequestMethod("POST");

con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
 "multipart/form-data;boundary=" + boundary);

DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
 + "name="file1";filename="" + newName + """ + end);
ds.writeBytes(end);

FileInputStream fStream = new FileInputStream(uploadFile);

int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;

while ((length = fStream.read(buffer)) != -1)
{

ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

fStream.close();
ds.flush();

I hope this article has been helpful to your Java programming.


Related articles: