SpringBoot文件(本地虚拟路径和远程ftp)上传

一、测试中图片上传到本地硬盘

     1、配置本地文件上传虚拟路径(二种方式)

      (1)方式一:yaml配置文件

server:
  port: 8081
#配置文件上传的虚拟路径
web:
  upload:
    img: C:/Users/wuchengfeng/Desktop/workplace/web/img/
spring:
  mvc:
    #访问图片、html等文件的根路径
    static-path-pattern: /img/**
  resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload.img}

 (2)方式二(使用代码)

@Configuration
public class MvcConfigure implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("file:C:/Users/wuchengfeng/Desktop/workplace/web/img/");
    }
}
@Configuration
public class WebConfigAdapter  extends WebMvcConfigurationSupport {
    @Value("web.upload.img")
    private String  locationPath;
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("img/**").
                addResourceLocations("file:"+locationPath);
        super.addResourceHandlers(registry);
    }
}

 2、文件上传

   (1)前端页面代码:

 <div style="width: 500px;height: 300px;border: antiquewhite solid 1px;padding-top: 10px;padding-left: 10px">

       <form  action="/pay/upload" method="post" enctype="multipart/form-data">
           <input type="file"   name="file"  id="fileId">
           <input type="submit" value="上传">
       </form>

       <img src="#" height="200px" width="300px" id="show_img" style="margin-top: 10px">

       <script  type="text/javascript">
           document.getElementById("fileId").onchange=function (ev) {
              document.getElementById("show_img").src=getImgPath(this.files[0]);
           }

           function getImgPath(file) {
               var url = null;
               if(window.createObjectURL !== undefined) {
                   url = window.createObjectURL(file);
               } else if(window.URL !== undefined) {
                   url = window.URL.createObjectURL(file);
               } else if(window.webkitURL !== undefined) {
                   url = window.webkitURL.createObjectURL(file);
               }
               return url;
           }
       </script>
   </div>

     (2)后端代码:

 @Value("${web.upload.img}")
    private String  baseDisPath;
    @RequestMapping("/pay/upload")
    @ResponseBody
    public String  upload(@RequestParam("file")MultipartFile file){
        String originFileName=file.getOriginalFilename();
        String uploadFileName=(new Date().getTime())+originFileName.substring(originFileName.lastIndexOf("."));
        try {
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(baseDisPath+uploadFileName)));
            return uploadFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

   二、远程FTP服务器文件上传

    1、Ftp服务器搭建(centos)

          (1)用 yum 安装 vsftpd(yum install -y vsftpd)

             

          (2)进入ftp目录,创建文件存储目录img

              

             手动上传一张图片放入img目录下面,测试用

             

             (3)ftp服务器启动(service vsftpd start)

             

             查看ftp服务器的端口

             

             浏览器访问ftp:ip:21/var/ftp/img/test.jpg

                   

                  (4)创建ftp用户组

                  

          2 、java代码

          (1)Ftp上传工具类 

public class FtpUtil {

	private  final static String  FTP_HOST="192.168.234.130";
	private  final static int     FTP_PORT=21;
	private  final static String  USER_NAME="ftpuser";
	private  final static String  PASS_WORD="123456";
	private  final static String  BASE_PATH="/img";


	/**
	 * Description:     向FTP服务器上传文件
	 * @param filename  上传到FTP服务器上的文件名
	 * @param input     输入流
	 * @return          成功返回true,否则返回false
	 */  
	public static boolean uploadFile(String filename, InputStream input) {
		boolean  result=false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(FTP_HOST, FTP_PORT);
			ftp.login(USER_NAME, PASS_WORD);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return false;
			}
			//切换到上传目录
			if (!ftp.changeWorkingDirectory(BASE_PATH))
				ftp.changeWorkingDirectory(BASE_PATH);
			//设置上传文件的类型为二进制类型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			//上传文件
			if (!ftp.storeFile(filename, input)) {
				return result;
			}
			input.close();
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}
		return result;
	}


	public static  String  getFileName(MultipartFile file){
		String originFileName=file.getOriginalFilename();
		return (new Date().getTime())+originFileName.substring(originFileName.lastIndexOf("."));
	}
}
 @RequestMapping("/pay/ftpUpload")
    @ResponseBody
    public String  ftpUploadFile(@RequestParam("ftpFile")MultipartFile ftpFile){
        String  res=FtpUtil.getFileName(ftpFile);
        boolean  b=false;
        try {
            b =FtpUtil.uploadFile(res,ftpFile.getInputStream());
            System.out.println("res==="+res+" 走了Ftp上传,"+(b?"上传成功":"上传失败"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b?"上传成功":"上传失败";
    }

猜你喜欢

转载自blog.csdn.net/fengchengwu2012/article/details/83340699