SSM项目中多文件上传(在java代码中利用ftp传输)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了SSM项目中多文件上传(在java代码中利用ftp传输),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含11318字,纯文字阅读大概需要17分钟。
内容图文
![SSM项目中多文件上传(在java代码中利用ftp传输)](/upload/InfoBanner/zyjiaocheng/750/e7ef841f6be046a99f6938d31e5c60aa.jpg)
ftp所需依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>1.4.1<version>
</dependency>
FTPClientUtils 工具类
package com.thinkgem.jeesite.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPClientUtils {
//ftp服务器地址
//String u = DictUtils.getDictValue("hostname", "ftp","106.15.124.251");
public String hostname = "106.15.124.251";
//ftp服务器端口号默认为21
//Integer p = Integer.parseInt(DictUtils.getDictValue("port", "ftp", "21"));
public Integer port = 21 ;
//ftp登录账号
//String n = DictUtils.getDictValue("username", "ftp","xxxxxxx");
public String username = "aaaa";
//ftp登录密码
//String pwd = DictUtils.getDictValue("password", "ftp","xxxxxxxx");
public String password = "123456abc";
public FTPClient ftpClient = null;
/**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println("connect failed...ftp服务器:"+this.hostname+":"+this.port);
}
System.out.println("connect successfu...ftp服务器:"+this.hostname+":"+this.port);
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
// ftpClient.enterLocalPassiveMode();//
ftpClient.enterLocalActiveMode();
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
boolean flag = false;
try{
System.out.println("开始上传文件");
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.enterLocalActiveMode();
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
//改变目录路径
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
System.out.println("进入文件夹" + directory + " 成功!");
} else {
System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
System.out.println("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
//判断ftp服务器文件是否存在
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//创建目录
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println("创建文件夹" + dir + " 成功!");
} else {
System.out.println("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String filename, String localpath){
boolean flag = false;
OutputStream os=null;
try {
System.out.println("开始下载文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return */
public boolean deleteFile(String pathname, String filename){
boolean flag = false;
try {
System.out.println("开始删除文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
System.out.println("删除文件成功");
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return flag;
}
public static void main(String[] args) {
FTPClientUtils ftp =new FTPClientUtils();
ftp.uploadFile("/US", "te111.png", "D://download//test111.png");
//ftp.downloadFile("/US", "test111.png", "D://");
// ftp.deleteFile("/US", "test111.png");
System.out.println("ok");
}
}
jsp文件:
<%@ page contentType="text/html;charset=UTF-8" %>
<%--<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>--%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${ctx}/ftpTransfer/upload" method="post" enctype="multipart/form-data">
<%-- <label>用户名:</label><input type="text" name="name"/><br/>--%>
<label>体检号:</label><input type="text" name="paraTJH000"/><br/>
<label>科室类型:</label><input type="text" name="paraKSLX00"/><br/>
<label>是否打印1或0:</label><input type="text" name="paraBDY000"/><br/>
<label>头 像1</label><input type="file" name="file"/><br/>
<label>头 像2</label><input type="file" name="file"/><br/>
<input type="submit" value="提 交"/>
</form>
</body>
</html>
控制层:
package com.thinkgem.jeesite.modules.xmsq.web;
import com.thinkgem.jeesite.common.domain.ResponseBo;
import com.thinkgem.jeesite.common.utils.CommonUtils;
import com.thinkgem.jeesite.common.utils.FTPClientUtils;
import com.thinkgem.jeesite.modules.common.aop.SystemLog;
import com.thinkgem.jeesite.modules.xmsq.service.FtpTransferService;
import com.thinkgem.jeesite.modules.xmsq.utils.XmsqUserUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@RequestMapping(value ="${adminPath}/ftpTransfer")
public class FtpTransferController {
protected Logger applog = Logger.getLogger("applog");
@Autowired
private FtpTransferService ftpTransferService;
/**
* 上传图片文件到ftp服务器
* @param request
* @return
* PEIS_ReportPictureManage.examItemPictureOperate
*/
@ResponseBody
@SystemLog(module = "ftpTransfer:upload")
@RequestMapping(value = {"upload"})
public Object upload(@RequestParam("file")MultipartFile[] file , @RequestParam Map<String,Object> params, HttpServletRequest request){
ResponseBo responseBo = ResponseBo.ok();
try {
params.put("paraOPFLAG", "0");//0新增 1修改 2删除 这里是新增 设置为0
/*params.put("paraTJH000", "1234567");
params.put("paraKSLX00", "US");
params.put("paraBMBH00", "90");
params.put("paraCZY000", "9999");
params.put("paraBDY000", "1");*/
if(!CommonUtils.isStringNull((String) params.get("paraTJH000"))){
responseBo = ResponseBo.error("体检号不能空");
return responseBo;
}
if(!CommonUtils.isStringNull((String) params.get("paraKSLX00"))){
responseBo = ResponseBo.error("科室类型不能为空");
return responseBo;
}
if(!CommonUtils.isStringNull((String) params.get("paraBDY000"))){
responseBo = ResponseBo.error("是否在报告上展示不能为空 1-展示,0-不展示");
return responseBo;
}
XmsqUserUtils.putBasicParameters(params);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String str = sdf.format(date);
FTPClientUtils ftp = new FTPClientUtils();
for (int i = 0; i < file.length; i++) {
if (!file[i].isEmpty()) {
InputStream is = file[i].getInputStream();
ftp.uploadFile("/"+params.get("paraKSLX00")+"/"+str+"/"+params.get("paraTJH000"),i+".jpg",is);
}
}
responseBo.put("data", params);
}catch (Exception e) {
responseBo = ResponseBo.error(e.getMessage(),e);
applog.error("上传图片失败" , e);
}
return responseBo;
}
@RequestMapping(value = "toUpload")
public String upload(HttpServletRequest request) {
return "modules/test/upload";
}
}
内容总结
以上是互联网集市为您收集整理的SSM项目中多文件上传(在java代码中利用ftp传输)全部内容,希望文章能够帮你解决SSM项目中多文件上传(在java代码中利用ftp传输)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。