一般我们做文件上传,都是在页面上传到服务器。有时候,我们在做系统的时候,我们需要将文件先上传到我们自己的服务器,然后通过server-to-server的方式上传文件到另一个服务器,如云存储服务器。java中利用httpclient可以实现get,post等http请求,但是如果需要上传文件,需要结合httpmime,将文件作为二进制流加入到post请求体中,这里介绍如何通过httpclient将文件上传到服务器上。
这里开启一个struts2的工程,里面有保存文件上传的方法,将该服务作为httpclient最终需要上传的服务器。关键代码:
package com.xxx.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class MainAction {
private File image;
private String imageFileName;
private String imageContentType;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
pu