前言:此功能主要用于独立文件上传使用,本人主要用于配合jenkins自动化文件传输更新应用使用,因另外一台linux服务器开不了ftp服务才除此下策~
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/uploadDo")
public class UploadDo extends HttpServlet{
protected void doPost(HttpServletRequest request,HttpServletResponse response){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try{
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while(iter.hasNext()){
FileItem item = (FileItem)iter.next();
if(item.getName().indexOf(".war")!=-1){
File file = new File("");
String filePath = this.getClass().getClassLoader().getResource("").getPath();
filePath = filePath.substring(0,filePath.indexOf("UploadFile"));
File target = new File(filePath+"/"+item.getName());
item.write(target);
String targetPath = filePath.substring(0,filePath.indexOf("UploadFile"));
try{
new ProcessBuilder("sh","/c","mv "+target.getAbsolutePath()+" "+targetPath).start();
}catch(Exception e){
new ProcessBuilder("cmd.exe","-c","move "+target.getAbsolutePath()+" "+targetPath).start();
}
}
}
}catch(Exception e){
}
}
}
附上curl调用请求命令:
curl http://localhost:8080/UploadFile/uploadDo -F "file=@H:\1.war" -H "token: 222" -v
方法中需要的jar:点击下载
这篇博客介绍了web服务的文件上传接口功能,特别是如何在jenkins自动化流程中使用该功能进行文件传输,替代无法开启FTP服务的场景。文中还提供了一个curl调用请求命令的示例。
931

被折叠的 条评论
为什么被折叠?



