import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Util {
public final static String CRLF = "\r\n";
static public void uploadFile(String url, String host, String mimeType, String fieldName, File file, Socket sock, boolean debug) throws IOException {
String fileName = file.getName();
FileInputStream is = new FileInputStream(file);
byte[] fileBytes = new byte[(int) file.length()];
is.read(fileBytes);
is.close();
uploadByteArray(url, host, mimeType, fieldName, fileBytes, fileName, sock, debug);
}
static public void uploadByteArray(String url, String host, String mimeType, String fieldName, byte[] fileBytes, String fileName, Socket sock, boolean debug) {
String boundary ="---------------------------" + System.currentTimeMillis();
String boundaryHeader = "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"";
boundaryHeader += CRLF;
boundaryHeader += "Content-Type: " + mimeType + CRLF + CRLF;
long contentLength = fileBytes.length +
(boundary + CRLF).length() +
boundaryHeader.length() +
(CRLF + boundary + CRLF).length() + "--".length() * 3;
String header = "POST " + url + " HTTP/1.1" + CRLF;
header += "Host: " + host + CRLF;
header += "Content-Type: multipart/form-data; boundary=" + boundary + CRLF;
header += "Content-Length: " + contentLength + CRLF;
header += CRLF;
try {
OutputStream os = sock.getOutputStream();
os.write(header.getBytes());
if(debug) System.out.print(header);
os.write(("--" + boundary + CRLF).getBytes());
if(debug) System.out.print("--" + boundary + CRLF);
os.write(boundaryHeader.getBytes());
if(debug) System.out.print(boundaryHeader);
os.write(fileBytes);
if(debug) System.out.print(new String(fileBytes));
os.write((CRLF + "--" + boundary + "--" + CRLF).getBytes());
if(debug) System.out.print(CRLF + "--" + boundary + "--" + CRLF);
os.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
}