spring boot使用nginx和ftp服务器实现图片上传下载(windows server)

本人使用的springboot为1.5.6版本

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

maven依赖为:

<commons-lang3.version>3.3.2</commons-lang3.version>
		<commons-io.version>1.3.2</commons-io.version>
		<commons-net.version>3.3</commons-net.version>
		<commons-fileupload.version>1.3.1</commons-fileupload.version>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> 
			</dependency> -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!--启用不严格检查html -->
		<dependency>
			<groupId>net.sourceforge.nekohtml</groupId>
			<artifactId>nekohtml</artifactId>
			<version>1.9.22</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- Apache工具组件 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${commons-lang3.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>${commons-net.version}</version>
		</dependency>
		<!-- httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>${httpclient.version}</version>
		</dependency>
		<!-- MySql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>
		<!-- 连接池 -->
		<!-- Spring -->
		<!-- 文件上传组件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${commons-fileupload.version}</version>
		</dependency>

application.properties配置:

#ftp\u76F8\u5173\u914D\u7F6E    
FTP_ADDRESS=你的服务器
FTP_PORT=商品
FTP_USERNAME=你的用户名
FTP_PASSWORD=你的密码
FTP_BASE_PATH=images
#\u56FE\u7247\u670D\u52A1\u5668\u76F8\u5173\u914D\u7F6E   

IMAGE_BASE_URL=images

NG_BASE_PATH=10021

server.port=8015
server.context-path=/demo
spring.thymeleaf.mode=LEGACYHTML5

controller:

@ResponseBody
	@RequestMapping("upload")
	public String pictureUpload(@RequestParam(value = "file") MultipartFile uploadFile) {
		long begin = System.currentTimeMillis();
		String json = "";
		try {
			Map result = pictureService.uploadPicture(uploadFile);
			// 浏览器擅长处理json格式的字符串,为了减少因为浏览器内核不同导致的bug,建议用json
			json = new ObjectMapper().writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		log.info("定时任务结束,共耗时:[" + (end-begin) + "]毫秒");
		return json;
		
	}

service:

@Override
	public Map uploadPicture(MultipartFile uploadFile) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String date = sdf.format(new Date());
		Map resultMap = new HashMap<>();
		try {
			// 1. 取原始文件名
			String oldName = uploadFile.getOriginalFilename();
			String suffix = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
			// 2. ftp 服务器的文件名
			String newName = date + "." + suffix;
			// 图片上传
			boolean result = uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, uploadFile.getInputStream(),
					FTP_BASE_PATH, newName);
			// 返回结果
			if (!result) {
				resultMap.put("error", 1);
				resultMap.put("message", "upload Fail");
				return resultMap;
			}
			resultMap.put("error", 0);
			resultMap.put("url", IMAGE_BASE_URL + "/" + newName);
			return resultMap;

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("error", 1);
			resultMap.put("message", "upload Fail");
			return resultMap;
		}
	}

	/**
	 * ftp 上传图片方法
	 * 
	 * @param ip
	 *            ftp 服务器ip地址
	 * @param port
	 *            ftp 服务器port,默认是21
	 * @param account
	 *            ftp 服务器用户名
	 * @param passwd
	 *            ftp 服务器密码
	 * @param inputStream
	 *            文件流
	 * @param workingDir
	 *            ftp 服务器存储图片的绝对路径
	 * @param fileName
	 *            上传到ftp 服务器文件名
	 * @throws Exception
	 * 
	 */
	public boolean uploadFile(String ip, Integer port, String account, String passwd, InputStream inputStream,
			String workingDir, String fileName) throws Exception {
		boolean result = false;
		// 1. 创建一个FtpClient对象
		FTPClient ftpClient = new FTPClient();
		try {
			// 2. 创建 ftp 连接
			ftpClient.connect(ip, port);
			// 3. 登录 ftp 服务器
			ftpClient.login(account, passwd);
			int reply = ftpClient.getReplyCode(); // 获取连接ftp 状态返回值
			System.out.println("code : " + reply);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect(); // 如果返回状态不再 200 ~ 300 则认为连接失败
				return result;
			}
			// 4. 读取本地文件
			// FileInputStream inputStream = new FileInputStream(new
			// File("F:\\hello.png"));
			// 5. 设置上传的路径
			ftpClient.changeWorkingDirectory(workingDir);
			// 6. 修改上传文件的格式为二进制
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			// 7. 服务器存储文件,第一个参数是存储在服务器的文件名,第二个参数是文件流
			if (!ftpClient.storeFile(fileName, inputStream)) {
				return result;
			}
			// 8. 关闭连接
			inputStream.close();
			ftpClient.logout();
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// FIXME 听说,项目里面最好少用try catch
			// 捕获异常,这样会导致Spring的事务回滚出问题???难道之前写的代码都是假代码!!!
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}

下面是nginx配置:

${nginx}/conf/nginx.conf中添加:

server {
        listen 8088;
        server_name localhost;
        location / {
            #    存放图片的地址
            root D:/images;
            index *.*;
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers X-Requested-With;
            add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
        }
    }

测试nginx:命令:  nginx -t

配置ftp服务器请百度。

end.






文章来源: spring boot使用nginx和ftp服务器实现图片上传下载(windows server)

人吐槽 人点赞

猜你喜欢

发表评论

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:spring boot使用nginx和ftp服务器实现图片上传下载(windows server)