Springmvc–FTP服务器文件上传

  • Post author:
  • Post category:其他




Springmvc–FTP

服务器文件上传



第一步:

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<File> 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<File> 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 *;

}

}



版权声明:本文为luomingyi2016原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。