【问题标题】:Upload file to a website using Java使用 Java 将文件上传到网站
【发布时间】:2016-12-14 22:34:44
【问题描述】:

我不完全确定这是否可行,但我想将文件上传到我创建的网站。我想上传这个文件,只使用 Java,没有真正的个人帮助。我的意思是用户将能够单击应用程序,然后应用程序将完成其余的工作。 所以假设我有一个像final static File file = new File (”file.txt”); 这样的文件的变量,然后以某种方式连接到像http://example.com/ 这样的网站,然后会有一个表格来上传文件。然后代码会将file.txt 上传到表单并提交。 从理论上讲,这似乎是可能的,但我不完全确定从哪里开始以及是否有任何 Jar 库或已经编写的代码,这可能会有所帮助。如果这是不可能的,我想知道是否有任何其他可能的方式,可以以另一种方式实现同​​样的事情。

【问题讨论】:

  • “没有真正的个人帮助”是什么意思?
  • @chrylis 我很欣赏这个问题,我只是说它应该能够一键自行运行。用户不应该点击多个东西来上传一个文件,只需点击一下,应用程序就会完成剩下的工作。
  • 你也在写后端吗?
  • @chrylis 如果您指的是网站、表单和提交 (PHP),那么可以。

标签: java file file-upload upload submit


【解决方案1】:

此链接可能对您有用: http://commons.apache.org/proper/commons-fileupload/

Commons FileUpload 包使您可以轻松地将强大的高性能文件上传功能添加到您的 servlet 和 Web 应用程序中。

【讨论】:

  • 感谢反馈,其实我不知道commons.apache包有文件上传包。
【解决方案2】:

使用Apache HttpComponents 可以更轻松地完成此操作。我建议使用它,因为 Java 的 http 客户端不是很好。如果您不想使用 3rd 方库,您可以找到更复杂且不太健壮的版本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是上传文件的URL,String parameter是http post请求的参数名,File file是要上传的文件。

【讨论】:

  • 非常感谢您的反馈,我会尝试一下,看看它是否有效并返回。
  • @fkrottenkirk 当然!啊,我的错!我刚刚意识到我将它设置为void,但它应该返回一个字符串。更新了答案。
  • 我已经导入了包和代码,在声明url、参数和文件时,我应该在函数之外执行还是如何?代码的很大一部分也有条纹。
  • @fkrottenkirk 好的。所以现在,要上传文件,您运行uploadFile("http://example.com/uploadfile.php", "file", file) 并更改字段以满足您的需求。参数是包含文件的 POST 参数。不过,我不知道您的应用程序将其设置为什么。我不知道绿色条纹,但这是功能(在另一个来源希望避开绿色的东西)gist.github.com/Arinerron/1fc812f62d4679c70eae85682ff4607d
  • 好的,所以目前我的代码在这个链接中看起来像 pastebin.com/85Fw0Gtn 我已经注释掉了错误在哪里以及它们是什么。
【解决方案3】:

试试看: STEP1:为事件创建和接口。

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();

【讨论】:

  • 我真的很感激这个答案,发生了很多事情。我可以看到您已经添加了我必须更改的位置、URL 和文件,但不应该还有一个地方让我输入表单或文件上传字段的名称吗?
  • 是的。您可以使用方法示例:addVariable("key", "value") example for this example upload.addVariable("var1", "hello");
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多