spring MultipartFile 文件(图片)上传

本篇完全是个人记录,以便复制粘贴

/**
 * 设备控制类
 * @version 0.0.1
 * @since 2018年9月6日
 */
@RestController
@RequestMapping("/device")
public class DeviceController {
/**
	 * 添加设备
	 * @param deviceGroupId 设备分组ID
	 * @param deviceType 设备类型
	 * @param serialNumber 设备序列号
	 * @param voucher 设备凭证
	 * @param location 设备所在位置
	 * @param owner 设备所有者身份
	 */
	@RequestMapping(value = "/save/{deviceGroupId}/{deviceType}/{serialNo}", method = { RequestMethod.POST })
	public @ResponseBody String save(@PathVariable Long deviceGroupId, @PathVariable String deviceType,
			@PathVariable String serialNo, @RequestParam MultipartFile upfile, @Valid Device device) {

		AppResult appResult = new AppResult();
		JsonHelper helper = new JsonHelper();
		logger.info("------device save request param>:[deviceGroupId={},deviceType={},serialNo={},getOwner={}]",
				deviceGroupId, deviceType, serialNo, device.getOwner());
		try {

			// 先判断上传文件是否为图片
			String fileName = upfile.getOriginalFilename();
			if (FileUploadUtil.isImage(fileName)) {
				String updateFileName = DateUtils.convertDateToString(DateUtils.getCurrentDate(),
						DateUtils.DATE_TIME_PATTERN) + "-" + serialNo;
				
				// path文件指定的路径
				String path = WebConstant.FILE_UPLOAD_URL;
				
				String retUrl = FileUploadUtil.upload(upfile,path , updateFileName);
				
				String voucher = retUrl.replace(path, "");
				device.setVoucher(voucher);
				deviceService.save(device);
			} else {
				appResult.setCode(WebConstant.UPLOAD_FILE_NO_IMAGE);
				appResult.setMessage(WebConstant.checkCode(WebConstant.UPLOAD_FILE_NO_IMAGE));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("--------device save error info>:{}" ,e);
			appResult.setCode(AppCodeConstant.ERROR);
			appResult.setMessage(AppCodeConstant.checkCode(AppCodeConstant.ERROR));
		}
		return helper.toJsonStr(appResult);
	}
}
package com.launch.diagdevice.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtil {

	
//	private static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
	
	/**
	 * file是文件
	 * path 上传之后的文件路径
	 * updateFileName 修改之后的文件名,不包括后缀,为修改可传null
	 */
	public static String upload(MultipartFile file, String path, String updateFileName) {
		String dirPath = "";
		try {
			String fileName = file.getOriginalFilename();

			// 得到文件后缀
			int pos = fileName.lastIndexOf(".");
			String extName = fileName.substring(pos + 1);

			// 判断上传文件必须是zip或者是rar否则不允许上传
			/*
			 * if (!extName.equals("zip") && !extName.equals("rar")) { return
			 * "-1"; }
			 */

			// 一个用户一个文件夹
//			path = path + File.separator + userId;
//			path = path + File.separator ;

			File descFile = new File(path);
			if (!descFile.exists()) {
				descFile.mkdirs();
			}

			// 是否保留原来的文件名
			if (!StringUtils.isEmpty(updateFileName)) {
				fileName = updateFileName + "." + extName;
			}
			// 根据服务器的文件保存地址和原文件名创建目录文件全路径
			dirPath = path + File.separator + fileName;

			File pushFile = new File(dirPath);
			// 传输文件
			file.transferTo(pushFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dirPath;

	}

	public static boolean isImage(String fileName) {
		boolean isFlag = fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".bmp")
				|| fileName.endsWith(".gif") || fileName.endsWith(".png");

		return isFlag;
	}
	

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于Spring框架,可以使用Apache Commons Net库来进行FTP文件的下载和上。下面是一个简单的示例代码: 1. 下载文件: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; public class FtpDownloadExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; String remoteFilePath = "/path/to/remote/file.txt"; String localFilePath = "/path/to/local/file.txt"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); boolean success = ftpClient.retrieveFile(remoteFilePath, new FileOutputStream(localFilePath)); if (success) { System.out.println("文件下载成功!"); } else { System.out.println("文件下载失败!"); } ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` 2. 上MultipartFile文件: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.springframework.web.multipart.MultipartFile; public class FtpUploadExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; String remoteFilePath = "/path/to/remote/file.txt"; MultipartFile multipartFile = ...; // 从请求中获取上MultipartFile对象 FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); InputStream inputStream = multipartFile.getInputStream(); boolean success = ftpClient.storeFile(remoteFilePath, inputStream); inputStream.close(); if (success) { System.out.println("文件成功!"); } else { System.out.println("文件失败!"); } ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` 请根据实际情况修改代码中的服务器地址、端口、用户名、密码、文件路径等参数。希望对您有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值