我不完全确定这是否可行,但我想将文件上传到我创建的网站。我想上传这个文件,只使用Java而没有真正的个人帮助。我的意思是用户可以单击该应用程序,然后应用程序将完成剩下的工作。
所以假设我有一个像final static File file = new File (”file.txt”);
这样的文件的变量,然后以某种方式连接到像http://example.com/
这样的网站,然后有一个表格来上传文件。然后,代码会将file.txt
上传到表单并提交。
理论上似乎是可能的,但我不完全确定从哪里开始,是否有任何Jar库或已编写的代码,这可能有所帮助。如果这是不可能的,我想知道是否有任何其他可能的方式,这可能以另一种方式实现相同的目的。
答案 0 :(得分:1)
此链接可能对您有用: http://commons.apache.org/proper/commons-fileupload/
Commons FileUpload包可以轻松地为您的servlet和Web应用程序添加强大,高性能的文件上载功能。
答案 1 :(得分:0)
使用Apache HttpComponents可以更轻松地完成此操作。我建议使用它,因为Java的http客户端不是很好。如果您不想使用第三方库,则可以找到更复杂且不太健壮的版本on this post。以下是使用Apache HttpComponents的示例:
public String uploadFile(String url, String paramater, File file)
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart(parameter, cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
String response = response.getStatusLine();
httpclient.getConnectionManager().shutdown();
return response;
}
如果String url
是要将文件上传到的网址,String parameter
是http发布请求的参数名称,File file
是要上传的文件。
答案 2 :(得分:0)
试一试: 第1步:为事件创建和界面。
public interface IHTTPMultipart {
public void OnFileUploading(String fileName, long uploading, long filesize, float porcent);
public void OnFileUploaded(String fileName);
public void OnAllFilesUploaded();
public void OnDataReceived(byte[] content);
public void OnError(int codeError);
public void OnDownloadingData(long received, long max, float porcent);
}
步骤2:创建一个类上传器,实现IHTTPMultipart
的文件import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
* @author Owner
*/
public class HTTPMultipart implements Runnable {
private final String boundary = "===" + System.currentTimeMillis() + "===";
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset = "uft-8";
private final HashMap<String, String> variables = new HashMap<String, String>();
private final HashMap<String, File> files = new HashMap<String, File>();
private final String url;
private Thread th1 = null;
private IHTTPMultipart event = null;
private int buffer = 4096;
private int responseCode = -1;
private byte[] responseData = null;
private int timeOut = 120000;
HTTPMultipart(String url) {
this.url = url;
}
public void setEvent(IHTTPMultipart event) {
this.event = event;
}
public void setBuffer(int buffer) {
this.buffer = buffer;
}
public void setEncode(String enc) {
this.charset = enc;
}
public void addVariable(String key, String value) {
if (!variables.containsKey(key)) {
variables.put(key, value);
}
}
public void addFile(String key, File file) {
if (!files.containsKey(key)) {
files.put(key, file);
}
}
public void addFile(String key, String file) {
if (!files.containsKey(key)) {
files.put(key, new File(file));
}
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public int getResponseCode() {
return this.responseCode;
}
public byte[] getResponseData() {
return this.responseData;
}
public void send() {
th1 = new Thread(this);
th1.start();
}
@Override
public void run() {
try {
URL url1 = new URL(this.url);
httpConn = (HttpURLConnection) url1.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
if (this.timeOut>0){
httpConn.setConnectTimeout(this.timeOut);
}
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
StringBuilder str = new StringBuilder();
//Read all variables.
Iterator it = this.variables.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
str.append("--").append(boundary).append(LINE_FEED);
str.append("Content-Disposition: form-data; name=\"").append(String.valueOf(pairs.getKey())).append("\"")
.append(LINE_FEED);
str.append("Content-Type: text/plain; charset=").append(charset).append(
LINE_FEED);
str.append(LINE_FEED);
str.append(String.valueOf(pairs.getValue())).append(LINE_FEED);
}
OutputStream os = httpConn.getOutputStream();
os.write(str.toString().getBytes());
it = this.files.entrySet().iterator();
while (it.hasNext()) {
str = new StringBuilder();
Map.Entry pairs = (Map.Entry) it.next();
File file = (File) pairs.getValue();
String fieldName = String.valueOf(pairs.getKey());
String fileName = file.getName();
str.append("--").append(boundary).append(LINE_FEED);
str.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"")
.append(LINE_FEED);
str.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
str.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
str.append(LINE_FEED);
os.write(str.toString().getBytes());
FileInputStream inputStream = new FileInputStream(file);
byte[] buff = new byte[buffer];
int bytesRead;
long fileSize = file.length();
long uploading = 0;
while ((bytesRead = inputStream.read(buff)) != -1) {
os.write(buff, 0, bytesRead);
uploading += bytesRead;
if (event != null) {
float porcent = (uploading * 100) / fileSize;
event.OnFileUploading(fileName, uploading, fileSize, porcent);
}
}
inputStream.close();
if (event != null) {
event.OnFileUploading(fileName, fileSize, fileSize, 100f);
event.OnFileUploaded(fileName);
}
}
try {
os.flush();
} catch (Exception e) {
}
os.close();
if (event != null) {
event.OnAllFilesUploaded();
}
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis2 = new BufferedInputStream(httpConn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
long maxSize = httpConn.getContentLengthLong();
long received = 0l;
byte[] buf = new byte[buffer];
int bytesRead = -1;
while ((bytesRead = bis2.read(buf)) != -1) {
bos.write(buf, 0, bytesRead);
received += bytesRead;
if (event != null) {
float porcent = (received * 100) / maxSize;
event.OnDownloadingData(received, maxSize, porcent);
}
}
bis2.close();
bos.close();
this.responseCode = 0;
this.responseData = bos.toByteArray();
if (event != null) {
this.event.OnDataReceived(this.responseData);
}
} else {
this.responseCode = 998;
this.responseData = (httpConn.getResponseCode() + "").getBytes();
if (event != null) {
this.event.OnError(httpConn.getResponseCode());
}
}
} catch (Exception e) {
this.responseCode = 999;
this.responseData = e.getMessage().getBytes();
if (event != null) {
event.OnError(999);
}
}
}
}
第3步:测试代码。
String url = "add here your url http";
HTTPMultipart upload = new HTTPMultipart(url);
File file = new File("add here your file dir");
String variableName = "myFile";
//Add one file or more files.
upload.addFile(variableName, file);
//Add variable example
upload.addVariable("var1", "hello");
//Set the asyncronic events.
upload.setEvent(new Net.HTTP.IHTTPMultipart() {
@Override
public void OnFileUploading(String fileName, long uploading, long filesize, float porcent) {
}
@Override
public void OnFileUploaded(String fileName) {
}
@Override
public void OnAllFilesUploaded() {
}
@Override
public void OnDataReceived(byte[] content) {
}
@Override
public void OnError(int codeError) {
}
@Override
public void OnDownloadingData(long received, long max, float porcent) {
}
});
upload.send();