欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用ftp上传文件

程序员文章站 2022-03-11 20:13:29
...

因上传后查看的时候需要展示文件名称,所以数据设计的时候文件名称也是保存上的,下载的时候直接根据ftp服务器中的路径进行下载,此下载没有涉及到java代码,直接使用windows.open(url)进行下载的。
实现的话前端的是bootstarp ,先看图再看代码吧
使用ftp上传文件
使用ftp上传文件
上传的时候有个 添加上传文件 的按钮 ,每次点击都会新增一个上传项,点击修改的时候也需要把数据传下来展示,需要注意的就是点击上传项的话它对应的id每次是不一样的,需要把前面的上传项加上,否则修改页面展示修改的话会乱套。还有一个问题就是这个id在append中拼接是否生效转义的问题,后续代码中细看。
先看看页面中上传项及添加上传项的代码,添加上传项需要注意每次添加的id

这是一组上传项
<div class="form-group">
                            <label class="col-sm-2 control-label " style="margin-left: -0.7%">清单</label>
                            <input type="hidden" id="listingType" name="listingType" >
                            <input type="hidden" id="listingName" name="listingName" value="${listingName}">
                            <input type="hidden" id="listingUrl" name="listingUrl" value="${listingUrl}">
                            <div class="col-sm-2">
                                <input  type="file" name="listing" style="position: absolute;z-index: -1"
                                        onchange="OrderInfoDlg.uploadFile('listing','listingType','listingName','listingUrl','listingNames')"
                                        id="listing"/>
                                <button class="btn btn-success " onclick='javaScript:$("#listing").click()' type="button" style="position: absolute;z-index: 2"><i class="fa fa-upload"></i>&nbsp;&nbsp;<span class="bold">上传</span></button>
                                <span style="position: absolute;z-index: 1; padding: 8px 8px 8px 80px" id="listingNames" value="${listingName}">${listingName}</span>
                            </div>
                            <label class="col-sm-2 control-label " style="margin-left: 8%">隐蔽图纸</label>
                            <input type="hidden" id="drawingType" name="drawingType" >
                            <input type="hidden" id="drawingName" name="drawingName" value="${drawingName}">
                            <input type="hidden" id="drawingUrl" name="drawingUrl" value="${drawingUrl}">
                            <div class="col-sm-2">
                                <input  type="file" name="drawing" style="position: absolute;z-index: -1"
                                        onchange="OrderInfoDlg.uploadFile('drawing','drawingType','drawingName','drawingUrl','drawingNames')"
                                        id="drawing"/>
                                <button class="btn btn-success " onclick='javaScript:$("#drawing").click()' type="button" style="position: absolute;z-index: 2"><i class="fa fa-upload"></i>&nbsp;&nbsp;<span class="bold">上传</span></button>
                                <span style="position: absolute;z-index: 1; padding: 8px 8px 8px 80px" id="drawingNames" value="${drawingName}">${drawingName}</span>
                            </div>
                        </div>
                        <!-- 第二部分结束1 -->
                        <!-- 第三部分开始 -->
                        <a href='javascript:void(0)' style="margin-left: 6%" onclick='OrderInfoDlg.adUpLoadFile()'><u>添加上传文件</u></a>

添加上传文件 按钮 此处注意这个id的转义 需如下转义οnclick=‘javaScript:$("#file"+index+"").click()’

OrderInfoDlg.adUpLoadFile = function(){
    var length = $("#length").val();
    if(index==1) {
        index = parseInt(length) + index;
    }
    $("#adUpLoadFile").append(" <div class=\"form-group\">\n" +
        "                            <label class=\"col-sm-3 control-label \" style=\"margin-left: -9%\" >上传文件名称</label>\n" +
        "                            <div  class=\"col-sm-2\">\n" +
        "<!--                                <input type=\"hidden\" id=\"fileType${qualificationsUploadFileLP.index}\" name=\"fileType\" value=\"${qualificationsUploadFile.fileType}\">-->\n" +
        "                                <input type=\"hidden\" id='fileName"+index+"' name=\"fileName\" >\n" +
        "                                <input type=\"hidden\" id='fileUrl"+index+"' name=\"fileUrl\" >\n" +
        "                                <input  class=\"form-control\"  id='fileType"+index+"'   name=\"fileType\" >\n" +
        "                            </div>\n" +
        "                            <div class=\"col-sm-2\" >\n" +
        "<!--                                <input  type=\"file\" name=\"file\" multiple=\"multiple\"-->\n" +
        "<!--                                        οnchange=\"OrderInfoDlg.uploadFile('file${qualificationsUploadFileLP.index}','fileType${qualificationsUploadFileLP.index}','fileName${qualificationsUploadFileLP.index}','fileUrl${qualificationsUploadFileLP.index}')\"-->\n" +
        "<!--                                        id=\"file${qualificationsUploadFileLP.index}\"/>-->\n" +
        "                                <input  type=\"file\" name=\"file\" style=\"position: absolute;z-index: -1\"\n" +
        "                                        οnchange=\"OrderInfoDlg.uploadFile('file"+index+"','fileType"+index+"','fileName"+index+"','fileUrl"+index+"','fileNames"+index+"')\"\n" +
        "                                        id='file"+index+"'/>\n" +
        "                                <button class=\"btn btn-success \" οnclick='javaScript:$(\"#file"+index+"\").click()' type=\"button\" style=\"position: absolute;z-index: 2\"><i class=\"fa fa-upload\"></i>&nbsp;&nbsp;<span class=\"bold\">上传</span></button>\n" +
        "                                <span style=\"position: absolute;z-index: 1; padding: 8px 8px 8px 80px\" id='fileNames"+index+"'></span>\n" +
        "\n" +
        "                            </div>\n" +
        "                            <div  class=\"col-sm-3\" style=\"margin-left: 9%\">\n" +
        "                                <label class=\"col-sm-3 control-label\"><a href='javascript:void(0)' οnclick='OrderInfoDlg.deleteUpLoadFile(this)'><u>删除</u></a></label>\n" +
        "                            </div>\n" +
        "                        </div>");
    index++;

删除按钮

OrderInfoDlg.deleteUpLoadFile = function(obj){
    $(obj).parent().parent().parent().remove();
    index--;
}

上传js

OrderInfoDlg.uploadFile = function(id,type,name,url,span){
    var file = document.getElementById(id).files[0];
    var fileName = file.name;
    $("#"+span).html(fileName);
    document.getElementById(name).value = fileName;
    var formadta = new FormData();
    formadta.append("file",file);
    var ajax = new $ax(Feng.ctxPath + "/orderManager/uploadFile", function(data){
        if (data.validateResult === -1) {
            Feng.error(data.msg);
            return false;
        }else{
            document.getElementById(url).value = data.result;
        }
        Feng.success("上传成功!");
    },function(data){
        Feng.error("上传失败!");
    });
    ajax.setType();
    ajax.setData(formadta);
    ajax.start();
}

java代码使用ftp服务器

controller

  @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public Object uploadFile(@RequestParam(required = true) MultipartFile file) {
        String path = "";
        try {
            if (file == null)
                return null;
            path = UploadFileUtil.uploadZy(FTPConstants.PATH_ZY, file);
        }catch (Exception e){
            e.printStackTrace();
            return new ResultData("上传失败",ResultData.RESULT_CODE_VALIDATE_FAIL,path);
        }
        return new ResultData("上传成功",ResultData.RESULT_CODE_SUCCESS,path);
    }

UploadFileUtil

public class UploadFileUtil {

    public static String upload(MultipartFile file) {
        String path = file.getOriginalFilename();
        path = path.substring(path.lastIndexOf(".") + 1);
        path = UUID.randomUUID().toString().replaceAll("-", "").replace("_","") + "." + path;
        try {
            //System.out.println(file);
            CommonsMultipartFile cf = (CommonsMultipartFile) file;
            DiskFileItem fi = (DiskFileItem) cf.getFileItem();
            File f = fi.getStoreLocation();
            byte[] imageByte = FileCopyUtils.copyToByteArray(f);
            //File file=new File(UUID.randomUUID().toString().replaceAll("-",""));
            System.out.println(FTPFileUtil.uploadFile("images/small", path, imageByte));
            return FTPFileUtil.getHttpUrl()+"/images/small/" + path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static String uploadZy(String path_zy,MultipartFile file) {
        String path = file.getOriginalFilename();
        path = path.substring(path.lastIndexOf(".") + 1);
        path = UUID.randomUUID().toString().replaceAll("-", "").replace("_","") + "." + path;
        try {
            InputStream inputStream = file.getInputStream();
            System.out.println(FTPFileUtil.uploadFile(path_zy, path, inputStream));
            //FTPFileUtil.downLoad("zyfile/order/","1a42bb8e9506457a8b0c50104534631a.docx","C:\\Users\\admin\\Downloads");
            //FTPFileUtil.uploadFile("zyfile/order/", path, inputStream);
            //https://image.xjxclub.com/zyfile/order/18ff3abc409743e48924f82bdf807ead.jpg
            //return CommConstants.IMGURL + path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FTPConstants.PATH_ZY+path;

    }
    
    /**
     * 小程序活动图片上传
     * @param file
     * @param imagePath:图片路径
     * @return
     */
    public static String upload(MultipartFile file,String imagePath) {
    	String path = file.getOriginalFilename();
    	path = path.substring(path.lastIndexOf(".") + 1);
    	path = UUID.randomUUID().toString().replaceAll("-", "").replace("_","") + "." + path;
    	try {
    		//System.out.println(file);
    		CommonsMultipartFile cf = (CommonsMultipartFile) file;
    		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
    		File f = fi.getStoreLocation();
    		byte[] imageByte = FileCopyUtils.copyToByteArray(f);
    		//File file=new File(UUID.randomUUID().toString().replaceAll("-",""));
    		System.out.println(FTPFileUtil.uploadFile(imagePath, path, imageByte));
    		return FTPFileUtil.getHttpUrl()+"/"+imagePath+"/" + path;
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	return null;
    	
    }

    //直接传项目文件
    public static String uploadFile(File file) {
        String path = file.getName();
        //path = path.substring(path.lastIndexOf(".") + 1);
        //path = UUID.randomUUID().toString().replaceAll("-", "").replace("_","") + "." + path;
        try {

            File f = file;
            byte[] imageByte = FileCopyUtils.copyToByteArray(f);
            //File file=new File(UUID.randomUUID().toString().replaceAll("-",""));
            System.out.println(FTPFileUtil.uploadFile("images", path, imageByte));
            return FTPFileUtil.getHttpUrl()+"/images/" + path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}

FTPFileUtil

/**
 * ftp上传下载功能
 *
 * @author ch
 */
public class FTPFileUtil {
	// ftp配置文件路径
	private static String FILE_PATH;
	private static String JUMP_PATH;
	// ip地址
	private static String URL;
	// 端口号
	private static String PORT;
	// 用户名
	private static String USER_NAME;
	// 密码
	private static String PWD;

	private static String HTTP_URL;

	private static String JUMP_URL;
	// 初始化
	static {
		FILE_PATH = "configs/ftp.properties";
		JUMP_PATH = "configs/config.properties";
		URL = ReaderProUtil.readerValue(FILE_PATH, "ftp_url");
		PORT = ReaderProUtil.readerValue(FILE_PATH, "ftp_port");
		USER_NAME = ReaderProUtil.readerValue(FILE_PATH, "ftp_username");
		PWD = ReaderProUtil.readerValue(FILE_PATH, "ftp_password");
		HTTP_URL = ReaderProUtil.readerValue(FILE_PATH, "ftp_proxy_url");

        JUMP_URL = ReaderProUtil.readerValue(JUMP_PATH, "jump_url");
	}

	public static String getHttpUrl() {
		return HTTP_URL;
	}

	public static String getJumpUrl() {
		return JUMP_URL;
	}

	/**
	 * 根据ftp文件路径,上传到服务器上的名称,输入流上传文件
	 *
	 * @param ftp_path
	 *            ftp文件路径
	 * @param file_name
	 *            文件名
	 * @param in
	 *            输入流
	 * @return
	 */
	public static boolean uploadFile(String ftp_path, String file_name,
			byte[] in) {
		// 返回状态
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(URL);// 连接FTP服务器
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			boolean a=ftp.login(USER_NAME, PWD);// 登录
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setBufferSize(1024*1024);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			BufferedInputStream input = new BufferedInputStream(new ByteArrayInputStream(in));
			//FTPClient.enterLocalPassiveMode();这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据
			//tp server可能每次开启不同的端口来传输数据,但是在linux上,由于安全限制,可能某些端口没有开启,所以就出现阻塞
			ftp.enterLocalPassiveMode();
			//切换文件目录
			//boolean b=ftp.changeWorkingDirectory(ftp_path);
			//输入文件
			boolean c=ftp.storeFile(ftp_path+"/"+file_name, input);
			//退出
			ftp.logout();
			//success = a&&b&&c;
			success = a&&c;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//切断ftp连接
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	public static boolean uploadFile(String ftp_path,String file_name, InputStream in) {
		// 返回状态
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(URL);// 连接FTP服务器
			// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			boolean a=ftp.login(USER_NAME, PWD);// 登录
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setBufferSize(1024*1024);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return false;
			}
			//FTPClient.enterLocalPassiveMode();这个方法的意思就是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据
			//tp server可能每次开启不同的端口来传输数据,但是在linux上,由于安全限制,可能某些端口没有开启,所以就出现阻塞
			ftp.enterLocalPassiveMode();
			//切换文件目录
			//boolean b=ftp.changeWorkingDirectory(ftp_path);
			//输入文件
			ftp.makeDirectory(ftp_path);
			ftp.changeWorkingDirectory(ftp_path);
			boolean c=ftp.storeFile(file_name, in);
			//退出
			ftp.logout();
			//success = a&&b&&c;
			success = a&&c;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//切断ftp连接
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	/**
	 * 根据ftp相对路径,文件名,本地下载路径下载文件
	 * @param remotePath 相对路径
	 * @param file_name 服务器文件名文件名
	 * @param local_path 本地路径
	 * @return
	 */
	public static boolean downLoad(String remotePath, String file_name,String local_path){
		boolean success=false;
		FTPClient ftp = new FTPClient();
	    try {
	        int reply;
	        ftp.connect(URL);// 连接FTP服务器
	        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
	        ftp.login(USER_NAME, PWD);// 登录
	        ftp.enterLocalPassiveMode();
	        //设置成二进制
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
	        reply = ftp.getReplyCode();
	        if (!FTPReply.isPositiveCompletion(reply)) {
	            ftp.disconnect();
	            return success;
	        }
	        ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录


	        FTPFile[] fs = ftp.listFiles();

	        for(FTPFile ff:fs){
	            if(ff.getName().equals(file_name)){
	            	//本地文件
	                File localFile = new File(local_path+"/"+ff.getName());
	                //输出流
	                OutputStream is = new FileOutputStream(localFile);
	                BufferedOutputStream out = new BufferedOutputStream(is);
	                ftp.setBufferSize(1024*1024);
	                ftp.retrieveFile(ff.getName(), out);
	                is.close();
	            }
	        }
	        ftp.logout();
	        success = true;
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (ftp.isConnected()) {
	            try {
	                ftp.disconnect();
	            } catch (IOException ioe) {
	            }
	        }
	    }
		return success;
	}
	public static void main(String[] args)
	{
		//downLoad("images","test.jpg","E:/test");
		//http://221.226.33.126:8080/XFX/images
		//111.png
	}


	public static void downURLImg(String imgPath, HttpServletResponse response){
		if(StringUtils.isEmpty(imgPath)) return;
		InputStream is = null;
		OutputStream os = null;
		HttpURLConnection httpURLConnection = null;
		try{
			imgPath =imgPath.replaceAll("\\\\", "/");
			File file = new File(imgPath);
			String fileName = file.getName();
			response.reset(); // 清空response
			response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes())); // 设置response的Header
			response.setContentType("application/octet-stream");
			URL url = new URL(imgPath);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(5000);//设置网络连接超时时间
			httpURLConnection.setDoInput(true);//设置应用程序要从网络连接读取数据
			httpURLConnection.setRequestMethod("GET");//设置方式
			int responseCode = httpURLConnection.getResponseCode();//获取相应code
			if(responseCode==200){
				is = httpURLConnection.getInputStream();//从服务器返回一个输入流
				os = new java.io.BufferedOutputStream(response.getOutputStream());
				byte[] buffer = new byte[httpURLConnection.getContentLength()];
				int len ;
				while((len=is.read(buffer,0, buffer.length))!=-1){
					os.write(buffer, 0, len);
				}
			}

		}catch(Exception e){
			e.printStackTrace();
			System.out.println("下载图片失败:"+e.getMessage());
		}finally{
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void delFiel(String tempfilepath){

		InputStream fis;
		try {
			fis = new FileInputStream(tempfilepath);

			if (null != fis)
			{

				fis.close();

				// 删除服务器上的文件
				if (null != tempfilepath)
				{
					File file = new File(tempfilepath);

					if(file.exists())
					{
						file.delete();
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

ftp.properties文件

ftp_url=IP
ftp_port=端口
ftp_username=名称
ftp_password=密码
ftp_proxy_url= https://image.xyg.com 代理访问路径前缀

至此 上传文件就解决了。上面第一个页面就包含上传和修改,只不过有数据的时候展示没有的时候上传
接下来说一下下载展示,这个页面是一个单独的下载页面,进入这个页面就和修改页面一样,只不过它有下载按钮可以下载
首先说一下页签 tab栏 最上面那部分,有优先顺序,看看标签中的设置
使用ftp上传文件
部分代码 页签 及下载的

<ul class="nav nav-tabs">
                            <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true"> 基础信息</a>
                            </li>
                            <li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="false">延保信息</a>
                            </li>
                            <li class=""><a data-toggle="tab" href="#tab-3" aria-expanded="false">楼盘信息</a>
                            </li>
                            <li class=""><a data-toggle="tab" href="#tab-4" aria-expanded="false">项目信息资质</a>
                            </li>
                        </ul>

下载部分

<div class="form-group">
    
	<div class="col-sm-6">
	<label class="col-sm-4 control-label " style="margin-left: -0.7%">${qualificationsUploadFiles[i*2].fileType}</label>&nbsp;
	<button type="button" class="btn btn-danger"  onclick="download('${qualificationsUploadFiles[i*2].fileUrl}')">
		<i class="fa fa-arrow-down"></i>&nbsp;下载
	</button>
	</div>

	<div class="col-sm-6">
	<label class="col-sm-4 control-label " style="margin-left: -12%">${qualificationsUploadFiles[i*2+1].fileType}</label>
	<button type="button" class="btn btn-danger" onclick="download('${qualificationsUploadFiles[i*2+1].fileUrl}')">
		<i class="fa fa-arrow-down"></i>&nbsp;下载
	</button>
	</div>
                                             
 </div>

js实现下载

<script type="text/javascript">
    function download(url) {
        window.open(url);
    }
</script>

至此完结