1. 程式人生 > >SpringBoot檔案(本地虛擬路徑和遠端ftp)上傳

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?"上傳成功":"上傳失敗";
    }