java中如何将多个文件从一个服务器发送到另外一个服务器,关键代码如下:
发送端代码
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.client.methods.HttpPost;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public @ResponseBody String uploadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
List<byte[]> fileByteArrList = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件
MultipartFile mf = entity.getValue();
if (fileByteArrList == null) {
fileByteArrList = new ArrayList<byte[]>();
}
fileByteArrList.add(mf.getBytes());
}
if (fileByteArrList == null) {
return "请上传文件";
}
//将多个文件装入到DataOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
for(byte[] bt : clazzes){
dos.writeInt(bt.length);
dos.write(bt);
}
byte[] fileByteArray = bos.toByteArray();
send(/*这里的url简略*/url, fileByteArray);
return "发送成功";
}
public String post(String url, byte[] paramByte) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(paramByte));
return httpclient.execute(httpPost, responseHandler);
}
接收端代码
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
@RequestMapping(value = "/acceptFiles", method = RequestMethod.POST)
public @ResponseBody String acceptFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {
/**简略掉如何从request中取到byte[] fileByteArray**/
//从DataInputStream中转换出来
ByteArrayInputStream bis = new ByteArrayInputStream(fileByteArray);
DataInputStream dis = new DataInputStream(bis);
int count = 0;
List<byte[]> fileByteList = new ArrayList<>();
while (count < fileByteArray.length) {
int length = dis.readInt();
count += 4;
byte[] bb = new byte[length];
count += dis.read(bb);
fileByteList.add(bb);
}
//最终行到fileByteList,下面就是业务操作了
}