网站首页> 博客> Springmvc--FTP服务器文件上传

Springmvc--FTP服务器文件上传

好文 1522
luomingyi
luomingyi 2018-01-01
收藏

第一步:index.jsp文件

springmvc上传文件

<form name="form1"     action="${pageContext.request.contextPath }/productManagerCo ntroller/upload.action" method="post"  enctype="multipart/form-data">

    <input type="file" name="upload_file" />

    <input type="submit" value="springmvc上传文件" />

form>

simditor富文本图片上传文件

<form name="form2"   action="${pageContext.request.contextPath }/productManagerControl ler/rich_file_upload.action" method="post"     enctype="multipart/form-data">

    <input type="file" name="upload_file" />

    <input type="submit" value="富文本图片上传文件" />

form>

注意:1.enctype="multipart/form-data" springmvc提供的文件上传MultipartFile类需要对应写的,表示上传文件的类型,name="upload_file"controller里的@RequestParam(value = "upload_file",required = false)MultipartFile file对应。

 

第二步:controller

/***

 *

 * @param file

 * @return

 * MultipartFile是springmvc的文件上传类

 * 通过request拿到上下文?

 */

/**文件上传*/

@RequestMapping("upload")

@ResponseBody

public ServerData upload(HttpSession session,@RequestParam(value =       "upload_file",required = false)MultipartFile       file,HttpServletRequest request){


String path = request.getSession().getServletContext()

.getRealPath("upload");

//文件会创建在webapp路径下

String targetFileName = ifileService.upload(file, path);

String url = PropertiesUtil.getPropertyMethod

("ftp.server.http.prefix")+targetFileName;

Map fileMap = new HashMap();

fileMap.put("uri", targetFileName);

fileMap.put("url", url);

return ServerData.createBySuccessData(fileMap);

}

/**simditor富文本文件上传*/

@RequestMapping("rich_file_upload")

@ResponseBody

public Map rich_file_upload(HttpSession session,

@RequestParam(value = "upload_file",required = false)

MultipartFile file,HttpServletRequest request,

HttpServletResponse response){

Map map = new HashMap();

//判断是否管理员

/*User user = (User)session.getAttribute("user");

if(user ==null ){


 * simditor富文本工具需要返回的数据格式

 * {"success": true/false,

"msg": "error message", # optional

"file_path": "[real file path]"

}

map.put("success", false);

map.put("msg", "需要管理员权限");

return map;

}*/

/*if(user!=null){

ServerData role = userService.isRole(user);

if(role.isSuccess()){*/

String path = request.getSession().getServletContext().getRealPath("upload");//文件会创建在webapp路径下

String targetFileName = ifileService.upload(file, path);

if(StringUtils.isBlank(targetFileName)){

map.put("success", false);

map.put("msg", "上传失败");

return map;

}

String url = PropertiesUtil.getPropertyMethod

("ftp.server.http.prefix")+targetFileName;

map.put("success", true);

map.put("msg", "上传成功");

map.put("file_path", url);

//此处我也不太懂,应该是与前端的约定,需要修改的地方

response.addHeader("Access-Control-Allow-Headers", "X-File-Name");

return map;

/*}*/

/*}

map.put("success", false);

map.put("msg", "无权限操作");

return map;    */

}

 

第三步:用于处理文件上传

@Service("fileServiceImpl")

public class FileServiceImpl implements IFileService{

Private Logger logger = LoggerFactory.

getLogger(FileServiceImpl.class);

/**上传文件*/

@Override

public String upload(MultipartFile file,String path){

//拿到上传文件的原始扩展名

String fileName = file.getOriginalFilename();

//拿到扩展名

String fileExtensionName = fileName.

substring(fileName.lastIndexOf(".")+1);

String uploadFileName =UUID.randomUUID().toString()+

"."+fileExtensionName;

logger.info("开始文件上传,上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,path,uploadFileName);

File fileDir = new File(path);

//判断文件名是否存在

if(!fileDir.exists()){

//赋予文件可读可写权限

fileDir.setWritable(true);

//创建目录

fileDir.mkdirs();

}

File targetFile = new File(path,uploadFileName);

try {

file.transferTo(targetFile);

//文件已经上传成功了


//todo targeFile上传到我们的FTP服务器上

FTPUtil.uploadFile(Lists.newArrayList(targetFile));

//todo 上传完之后,删除upload下面的文件

targetFile.delete();

} catch (IllegalStateException | IOException e) {

logger.error("上传文件异常",e);

return null;

}

());

return targetFile.getName();

}

}

 

 

 

 

第四步:连接FTP服务器

public class FTPUtil {

private static Logger logger = LoggerFactory.

getLogger(FTPUtil.class);


private static String ftpIp=PropertiesUtil.

getPropertyMethod("ftp.server.ip");

private static String ftpUser=PropertiesUtil.

getPropertyMethod("ftp.user");

private static String ftpPass=PropertiesUtil.

getPropertyMethod("ftp.pass");

private String ip;

private int port;//端口

private String user;

private String pwd;

private FTPClient ftpClient;

public FTPUtil(String ip,int port,String user,String pwd){

this.ip = ip;

this.port = port;

this.user = user;

this.pwd = pwd;

}

public static boolean uploadFile(List fileList){

FTPUtil ftpUtil = new FTPUtil(ftpIp, 21, ftpUser, ftpPass);

boolean result =false;

logger.info("开始连接FTP服务器");

try {

 result = ftpUtil.uploadFile("img", fileList);

} catch (IOException e) {

e.printStackTrace();

}finally{

logger.info("开始连接FTP服务器,结束上传,上传结果:");

}

return result;

}

public boolean uploadFile(String remotePath,List fileList) throws IOException{

boolean uploaded = true;

FileInputStream fis=null;

//连接FTP

if(connectServer(this.getIp(),this.getPort(),this.getUser(),this.getPwd())){

try {

//更改工作目录

ftpClient.changeWorkingDirectory(remotePath);

//设置缓冲区

ftpClient.setBufferSize(1024);

//设置编码格式

ftpClient.setControlEncoding("UTF-8");

//设置文件为二进制

ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);

ftpClient.enterLocalPassiveMode();

for(File fileItem : fileList){

fis = new FileInputStream(fileItem);

ftpClient.storeFile(fileItem.getName(), fis);

}

} catch (IOException e) {

uploaded = false;

logger.error("上传文件异常",e);

}finally{

//关闭资源

ftpClient.disconnect();

fis.close();

}

}

return uploaded;

}

//封装ftp连接的方法

public boolean connectServer(String ip,int port,String user,String pwd){

boolean isSuccess = false;

ftpClient = new FTPClient();

try {

ftpClient.connect(ip);

isSuccess = ftpClient.login(user, pwd);//输入账户和密码登录FTP服务器

} catch (Exception e) {

logger.error("连接FTP服务器异常",e);

}

return isSuccess;

}

public FTPClient getFtpClient() {

return ftpClient;

}

public void setFtpClient(FTPClient ftpClient) {

this.ftpClient = ftpClient;

}

public String getIp() {


return ip;

}

public void setIp(String ip) {

this.ip = ip;

}

public int getPort() {

return port;

}

public void setPort(int port) {

this.port = port;

}

public String getUser() {

return user;

}

public void setUser(String user) {

this.user = user;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

}

 

第五步:nginx配置

server {

    listen 80;

    autoindex off;

    server_name img.waxxh.me;

    access_log /usr/local/webserver/nginx/logs/access.log combined;

    index index.html index.htm index.jsp index.php;

    #error_page 404 /404.html;

    if ( $query_string ~* ".*[\;'\<\>].*" ){

        return 404;

    }

    location ~ /(mmall_fe|mmall_admin_fe)/dist/view/* {

        deny all;

    }

    location / {

        root /ftpfile/img/;//一有img.waxxh.me请求,就会转发到root 下的         /ftpfile/img/目录

        add_header Access-Control-Allow-Origin *;

    }

}


  • 没有任何评论
个评论
luomingyi

luomingyi (青铜)

10金币 (2)粉丝 (2)源码

 

加入微信群,不定期分享源码和经验
签到活跃榜 连续签到送额外金币
最新博客
校园跑腿系统外卖系统软件平台大学生创业平台搭建 969
壹脉销客智能名片CRM系统小程序可二开源码交付部署 1007
为啥没搞了 1534
Nginx 的 5 大应用场景,太实用了! 1720
CentOS 8-stream 安装Postgresql 详细教程 2024
JAVA智慧校园管理系统小程序源码 电子班牌 Sass 模式 1515
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 1295
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 1260
致远OA权限 2151
发博客会有金币吗 1321