java ssh 上传文件至服务器

时间:2024-04-16 09:22:17

java ssh 上传文件至服务器

@(JAVA)[上传文件至服务器]

private File upload; // 得到上传的文件
private String uploadContentType; // 得到文件的类型
private String uploadFileName; // 得到文件的名称
//省略get,set方法
	
private static final String LUN_WEN_ZHUAN_ZHU = "lun_wen_zhuan_zhu";
private static final String FILE_SEPARATOR = File.separator;
private static final String BASE_ATTACH_DIR = "attached";
	
public void jQueryFileUpload() throws Exception {
	String dirName = this.request.getParameter("dir");
	final String maxSizeStr = this.request.getParameter("maxSize");
	final String customFileName = this.request.getParameter("customFileName");
	final int maxSize = StringUtils.isNotEmpty(maxSizeStr) ? Integer.valueOf(maxSizeStr) : 500 * 1024 * 1024;
	dirName = StringUtils.isEmpty(dirName) ? LUN_WEN_ZHUAN_ZHU : dirName;
	String userInfo = "上传者未登录";
	final UserSession us = UserThreadLocal.getUserSession();
	// 不允许使用..移动到上一级目录
	if (dirName.indexOf("..") >= 0) {
		return;
	}
	this.response.setCharacterEncoding("UTF-8"); // 防止中文乱码
	this.response.setContentType("text/html; charset=UTF-8");
	final List<JqueryUploadData> results = Lists.newArrayList();
	boolean pass = false;
	FileInputStream fs = null;
	InputStreamReader isr = null;
	BufferedReader br = null;
	String text = null;
	// 为了照顾kindeditor
	final File file = this.upload;
	final String fName = this.uploadFileName;

	try {
		fs = new FileInputStream(file);
		isr = new InputStreamReader(fs);
		br = new BufferedReader(isr);
		while (true) {
			text = br.readLine();
			if (StringUtils.isNotBlank(text)) {
				break;
			}
		}
		// 读取文件有数据的第一行,判断若为jsp,html文件禁止上传
		if (text.contains("<%@page") || text.contains("<%") || text.contains("<!DOCTYPE") || text.contains("<?xml")
				|| text.endsWith("%>")) {
			if (us != null) {
				userInfo = "id:" + us.getUserId() + "登录名:" + us.getUserName() + "身份:" + us.getRoles();
			}
			LOGGER.info("有人上传非法文件!!!------" + userInfo + "文件名:" + fName + "已拦截要上传的路径:" + dirName + "/" + fName);
			pass = false;
		} else {
			pass = true;
		}
	} catch (final IOException e) {
		e.printStackTrace();
		pass = false;
	} finally {
		br.close();
		isr.close();
		fs.close();
	}

	if (!pass) {
		return;
	}

	final String originFileName = this.uploadFileName;
	// 检查扩展名
	final String fileExt = originFileName.substring(originFileName.lastIndexOf(".") + 1).toLowerCase();
	final String fileName = StringUtils.isNotEmpty(customFileName) ? customFileName + "." + fileExt
			: this.uploadFileName;
	if (us != null) {
		userInfo = "id:" + us.getUserId() + "登录名:" + us.getUserName() + "身份:" + us.getRoles();
	}
	LOGGER.info(userInfo + "-------->上传的文件的文件名为:" + fileName);
	// 检查文件大小
	if (file.length() > maxSize * 1000 * 1000) {
		// 删除无用文件
		FileUtils.deleteQuietly(file);
		LOGGER.error("-------->上传文件大小超过限制,当前允许的最大文件大小为:" + maxSize + "MB");
		final JqueryUploadData jud = new JqueryUploadData();
		jud.setError(1);
		jud.setMessage("上传文件大小超过限制, ,当前允许的最大文件大小为:" + maxSize + "MB");
		jud.setName(fileName);
		jud.setSize(file.length());
		results.add(jud);
	}

	final String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
	// 文件保存跟目录路径
	final PathSupport ps = this.generateSavePath(false, dirName, dateDir);
	// 构造目标文件名
	final String dstFileName = new Date().getTime() + "_" + fileName;
	final String dstFilePath = ps.getRealPath() + dstFileName;
	FileUtils.copyFile(file, new File(dstFilePath));
	LOGGER.info("保存上传附件:" + dstFilePath + "成功!");
	final JqueryUploadData jud = new JqueryUploadData();
	jud.setName(fileName);
	jud.setSize(file.length());
	jud.setDeleteType("DELETE");
	jud.setDeleteUrl("../common/kindeditor!jQueryRemove.action?jQuerydownloadName="
			+ URLEncoder.encode(ps.getRelativePath() + dstFileName, "UTF-8"));
	jud.setAttachment(ps.getRelativePath() + dstFileName);

	// for kindeditor
	jud.setError(0);
	jud.setMessage("上传成功");
	jud.setUrl(ps.getRelativePath() + dstFileName);
	jud.setFilename(fileName);

	results.add(jud);

	sendResponseMsg(new Gson().toJson(results));
}

private class JqueryUploadData {
	private String name;
	private long size;
	private String thumbnailUrl;
	private String deleteUrl;
	private String deleteType;
	private String type;
	private String attachment;
	private String url;
	private Integer error;
	private String message;
	private String filename;

	public String getName() {
		return this.name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public long getSize() {
		return this.size;
	}

	public void setSize(final long size) {
		this.size = size;
	}

	public String getUrl() {
		return this.url;
	}

	public void setUrl(final String url) {
		this.url = url;
	}

	public String getThumbnailUrl() {
		return this.thumbnailUrl;
	}

	public void setThumbnailUrl(final String thumbnailUrl) {
		this.thumbnailUrl = thumbnailUrl;
	}

	public String getDeleteUrl() {
		return this.deleteUrl;
	}

	public void setDeleteUrl(final String deleteUrl) {
		this.deleteUrl = deleteUrl;
	}

	public String getDeleteType() {
		return this.deleteType;
	}

	public void setDeleteType(final String deleteType) {
		this.deleteType = deleteType;
	}

	public String getType() {
		return this.type;
	}

	public void setType(final String type) {
		this.type = type;
	}

	public String getAttachment() {
		return this.attachment;
	}

	public void setAttachment(final String attachment) {
		this.attachment = attachment;
	}

	public Integer getError() {
		return this.error;
	}

	public void setError(final Integer error) {
		this.error = error;
	}

	public String getMessage() {
		return this.message;
	}

	public void setMessage(final String message) {
		this.message = message;
	}

	public String getFilename() {
		return this.filename;
	}

	public void setFilename(final String filename) {
		this.filename = filename;
	}
}

private class PathSupport {
	private String realPath;
	private String relativePath;
	private String url;

	public String getRealPath() {
		return this.realPath;
	}

	public void setRealPath(final String realPath) {
		this.realPath = realPath;
	}

	public void setRelativePath(final String relativePath) {
		this.relativePath = relativePath;
	}

	public String getRelativePath() {
		return relativePath;
	}

	public String getUrl() {
		return this.url;
	}

	public void setUrl(final String url) {
		this.url = url;
	}

	@Override
	public String toString() {
		return "PathSupport [realPath=" + this.realPath + ", relativePath=" + this.relativePath + ", url="
				+ this.url + "]";
	}

}

private PathSupport generateSavePath(final boolean isAccessory, final String dirName, final String dateDir) {
	String realPath = "";
	String relativePath = "";
	String filePathUrl = this.request.getScheme() + "://" + this.request.getServerName() + ":"
			+ this.request.getServerPort() + this.request.getContextPath() + "/";
	if (isAccessory == true) {
		realPath = ServletActionContext.getServletContext().getRealPath("/DownloadCenter/");
		relativePath += FILE_SEPARATOR + "DownloadCenter" + FILE_SEPARATOR;
		filePathUrl += "/DownloadCenter/";
	} else {
		realPath = ServletActionContext.getServletContext().getRealPath(BASE_ATTACH_DIR);
		realPath += FILE_SEPARATOR + dirName + FILE_SEPARATOR;
		relativePath += BASE_ATTACH_DIR + FILE_SEPARATOR + dirName + FILE_SEPARATOR;
		filePathUrl += BASE_ATTACH_DIR + "/" + dirName + "/";
		final File saveDirFile = new File(realPath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		// 构造日期目录
		if (StringUtils.isNotEmpty(dateDir)) {
			realPath += dateDir + FILE_SEPARATOR;
			relativePath += dateDir + FILE_SEPARATOR;
			filePathUrl += dateDir + "/";
			final File dirFile = new File(realPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
		}
	}
	final PathSupport ps = new PathSupport();
	ps.setRealPath(realPath);
	ps.setRelativePath(relativePath);
	ps.setUrl(filePathUrl);

	return ps;
}