- 工具类
FtpUtil.java
package com.bjsxt.utils;
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.util.UUID;
import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient;
public class FtpUtil {
public static String upload(String hostname,String username,String password, String basePath,String targetPath, String suffix,InputStream inputStream) throws SocketException, IOException { //实例化ftpClient FTPClient ftpClient = new FTPClient(); //1.连接服务器 ftpClient.connect(hostname); //2.登录(指定用户名和密码) ftpClient.login(username,password); //基本路径,一定存在 2017/03/22 String[] pathArray = targetPath.split("/"); for(String path:pathArray){ basePath+="/"+path; //3.指定目录 返回布尔类型 true表示该目录存在 boolean dirExsists = ftpClient.changeWorkingDirectory(basePath); //4.如果指定的目录不存在,则创建目录 if(!dirExsists){ //此方式,每次,只能创建一级目录 ftpClient.makeDirectory(basePath); } } //重新指定上传文件的路径 ftpClient.changeWorkingDirectory(basePath); //5.设置上传文件的方式 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //使用uuid,保存文件名唯一性 String uuid=UUID.randomUUID().toString(); /** * 6.执行上传 * remote 上传服务后,文件的名称 * local 文件输入流 * 上传文件时,如果已经存在同名文件,会被覆盖 */ ftpClient.storeFile(uuid+suffix,inputStream); //7.关闭资源 ftpClient.logout(); ftpClient.disconnect();
StringBuilder builder = new StringBuilder(); builder.append("http://"); builder.append(hostname+"/"); builder.append(targetPath+"/"); builder.append(uuid+suffix); return builder.toString(); }
/** * 根据文件名,获取文件后缀 * @param args * @throws SocketException * @throws IOException */ public static String getSuffix(String filename){ String suffix = ""; int fnum = filename.lastIndexOf("."); if(fnum>0){ suffix = filename.substring(fnum); } return suffix; }
public static void main(String[] args) throws SocketException, IOException { InputStream inputStream = new FileInputStream("E:/2017-03-22_105509.png"); String remoteFilename = upload("192.168.88.10", "ftpuser", "111111", "/home/ftpuser/www","/2017/03/22", ".png", inputStream); System.out.println(remoteFilename); } }
|
#文件上传property ftp.hostname=192.168.88.10 ftp.username=ftpuser ftp.password=111111 ftp.basePath=/home/ftpuser/www
|
- FileUploadService
FileUploadServiceImpl.java
package com.bjsxt.service.impl;
import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.util.Date;
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service;
import com.bjsxt.result.FileResult; import com.bjsxt.service.FileUploadService; import com.bjsxt.utils.DateUtil; import com.bjsxt.utils.FtpUtil;
@Service public class FileUploadServiceImpl implements FileUploadService {
/** * @Value是spring提供的标签,用于快捷获取properties属性值 */ @Value("${ftp.hostname}") String hostname; @Value("${ftp.username}") String username; @Value("${ftp.password}") String password; @Value("${ftp.basePath}") String basePath;
/** * 文件上传 * @throws IOException * @throws SocketException */ @Override public FileResult uploadFile(String suffix, InputStream inputStream) throws SocketException, IOException { String targetPath = DateUtil.getDateStr(new Date(), "yyyy/MM/dd"); //调用文件上传工具类 String fileUrl = FtpUtil.upload(hostname, username, password, basePath, targetPath, suffix,inputStream); return FileResult.success(fileUrl); }
}
|
- controller
FileUploadController.java
package com.bjsxt.controller;
import java.io.IOException;
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.ResponseBody; import org.springframework.web.multipart.MultipartFile;
import com.bjsxt.result.FileResult; import com.bjsxt.service.FileUploadService; import com.bjsxt.utils.FtpUtil;
@Controller @RequestMapping("/fileUpload") public class FileUploadController extends BaseController {
@Autowired FileUploadService fileUploadService;
/** * 保存上传文件 * @throws IOException */ @RequestMapping("/save") @ResponseBody public FileResult fileUploadSave(MultipartFile file) throws IOException{ //文件后缀 String suffix = FtpUtil.getSuffix(file.getOriginalFilename()); return fileUploadService.uploadFile(suffix,file.getInputStream()); }
}
|
- jsp页面
使用bootstrap fileinput插件
使用方法:
- 添加fileinput.css fileinput.js
- 初始化、回调函数
<script> //初始设置 language指定语言 uploadUrl指定文件上传的后台地址 allowedPreviewTypes允许上传文件的类型 $('#file-product-category').fileinput({ language: 'zh', uploadUrl: '${ctx}/fileUpload/save', allowedPreviewTypes : ['image', 'html', 'text', 'video', 'audio', 'flash'] }); //上传文件失败后 调用的方法(回调函数) $('#file-product-category').on('fileuploaderror', function(event, data, previewId, index) { var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader; console.log(data); console.log('File upload error'); }); //文件错误 比如文件类型错误 会调用此函数(回调函数) $('#file-product-category').on('fileerror', function(event, data) { console.log(data.id); console.log(data.index); console.log(data.file); console.log(data.reader); console.log(data.files); }); //文件上传成功之后 回调的函数 $('#file-product-category').on('fileuploaded', function(event, data, previewId, index) { var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader; alert(data.response.fileUrl); $("#image").val(data.response.fileUrl); console.log('File uploaded triggered'); }); </script> |
- debug无法关联原码
解决方法:
关联源码后,需要重新启动项目。