springboot上传图片,配置虚拟路径提供前端访问

最近在做springboot项目的时候,需要上传图片并且提供URL给前端。废话不多说,直接上代码。

首先在application.yml配置中添加如下配置

###服务启动端口号
server:
  port: 8003
  tomcat:
    uri-encoding: UTF-8
###文件上传
file: 
  ###静态资源对外暴露的访问路径
  staticAccessPath: /api/file/**
  ###静态资源实际存储路径
  uploadFolder: F:/upload/mall/
  uploadImage: image/
###项目名
  servlet:
     context-path:
     ###文件上传 
     multipart:
     enabled: true
     max-file-size: 10mb
     max-request-size: 10mb
###服务名称(服务注册到eureka名称)  
spring:
    application:
        name: test
    mvc:
        throw-exception-if-no-handler-found: true
        static-path-pattern: /**
    #静态资源访问
    resources:
        add-mappings: true
        static-locations: classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${file.uploadFolder}${file.uploadImage}
    http:
        encoding:
            force: true
            charset: utf-8
            enabled: true

然后新建一个类,继承WebMvcConfigurerAdapter

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SuppressWarnings("deprecation")
@Configuration
public class UploadFilePathConfig extends WebMvcConfigurerAdapter{
	
	@Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @Value("${file.uploadImage}")
    private String uploadImage;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:///" + uploadFolder + uploadImage);
        super.addResourceHandlers(registry);
    }

}

接着编写controller类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.snimay.entity.RetStruct;
import com.snimay.utils.FileUpload;
import com.snimay.utils.exception.MallException;
import com.snimay.utils.map.MapUtil;

@Controller
@RequestMapping("/fileupload/")
public class FileUploadController {
	
	//获取主机端口
	@Value("${server.port}")
    private String POST;
	//静态资源对外暴露的访问路径
	@Value("${file.staticAccessPath}")
    private String staticAccessPath;
	//实际存储路径
	@Value("${file.uploadFolder}")
    private String uploadFolder;
	//图片
	@Value("${file.uploadImage}")
    private String uploadImage;

	/**
	 * 获取所有文件上传前缀路径
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getSourceUrl.do", produces = "text/html;charset=UTF-8")
	public String getPrefixPath(HttpServletRequest request, HttpServletResponse response) {
		JSONObject resultObj = new JSONObject();
		JSONObject dataObj = new JSONObject();
		String fileUploadBackUrl = FileUpload.fileUploadBackUrl;
		dataObj.put("sourceUrl", fileUploadBackUrl + FileUpload.sourceDir);
		resultObj.put("code", 0);
		resultObj.put("msg", "获取所有路径成功");
		resultObj.put("data", dataObj);
		return resultObj.toString();
	}
	
	/**
	 * Description: 上传名片图片
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "uploadBusinessCardImage.do", produces = "text/html;charset=UTF-8")
	public String uploadBusinessCardImage(@RequestParam("file") MultipartFile file) {
		try {
			if (file.isEmpty()) {
				throw new MallException(-1,"上传文件为空");
			}
			
			String originalFilename = file.getOriginalFilename();
			String result = FileUpload.FileUpLoadAndGetParam(file, POST, staticAccessPath, uploadFolder, uploadImage, originalFilename);
			Map<String, Object> resultMap = JSONObject.parseObject(result.trim());
			Map<String, Object> layeditMap = new HashMap<>();
			if (resultMap.get("code").equals(0)) {
				Map<String, Object> resultDataMap = (Map<String, Object>) resultMap.get("data");System.out.println(resultDataMap);
				layeditMap.put("src", resultDataMap.get("http_url"));
				layeditMap.put("title", resultDataMap.get("file_name"));
				resultMap.put("data", layeditMap);
				resultMap.remove("param");

				result = resultMap.toString();
			}
			return result;
		} catch (Exception e) {
			return new RetStruct(-1, e.getMessage()).toString();
		}
	}


}

上传文件的工具类,最后返回结果封装为json格式

public class FileUpload {
	private static final Logger log = LoggerFactory.getLogger(FileUpload.class);
	public static String FILES_TYPE;
	public static String IMG_TYPE;
	public static int UPLOAD_MAX_SIZE;
	public static long UPLOAD_MAX_SIZE_BYTE;

	private Map<String, String> params;
	private Map<String, Object> mFilesUrlJSON = new HashMap<>();
	private static long fileSize = 0;
	private String errStr = "";

	static {
		InputStream is = null;
		try {
			Properties pro = new Properties();
			is = FileUpload.class.getResourceAsStream("/config.properties");
			pro.load(is);
			FILES_TYPE = FileType.getAllName();
			IMG_TYPE = ImgType.getAllName();
			UPLOAD_MAX_SIZE = pro.getProperty("uploadMaxSize") == null ? 2
					: Integer.parseInt(pro.getProperty("uploadMaxSize"));
			UPLOAD_MAX_SIZE_BYTE = UPLOAD_MAX_SIZE * 1024 * 1024;
			is.close();
		} catch (IOException e) {
			ILogUtil.info(e.getMessage());
			if (is != null) {
				try {
					is.close();
				} catch (IOException e1) {
					ILogUtil.info("关闭流出错.");
				}
			}
		}
	}
	
	/**
	 * Description:
	 * @param file 文件对象
	 * @param POST 端口号
	 * @param staticAccessPath 对外显示路径
	 * @param uploadFolder 上传文件夹的主路径
	 * @param filePath 上传文件的文件夹路径
	 * @param originalFilename 原始文件名称
	 * @return
	 */
	public static String FileUpLoadAndGetParam(MultipartFile file, String POST, String staticAccessPath, 
			String uploadFolder, String filePath, String originalFilename) {
		FileUpload fu = new FileUpload();
		if (!fu.writeFile(file, POST, staticAccessPath, uploadFolder, filePath, originalFilename)) {
			return RetResponse(10, "写文件失败," + fu.getErrStr());
		}
		JSONObject obj = fu.getFilesUrlJson();
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "上传成功");
		json.put("data", obj);
		json.put("param", fu.getParamsJson());
		return json.toString();
	}
	
	private boolean writeFile(MultipartFile file, String POST, String staticAccessPath, 
			String uploadFolder,String filePath, String originalFilename) {
		fileSize = file.getSize();
		File fileExists = new File(uploadFolder + filePath);
		
		try {
			if (!fileExists.exists()) {
				fileExists.mkdirs();
			}
		} catch (Exception e) {
			ILogUtil.info(e.getMessage());
			return false;
		}
		
		String oldFileName = originalFilename;
		if (!checkFile(oldFileName, FILES_TYPE)) {
			errStr = "校验文件类型失败,系统支持格式:" + FILES_TYPE;
			ILogUtil.info("校验文件类型失败");
			return false;
		}
		
		// 不是所有的上传文件都有扩展名,需要允许上传的文件没有扩展名
		String suffix = "";
		int index = oldFileName.lastIndexOf(".");
		if (index != -1) {
			suffix = oldFileName.substring(index);
		}
		
		// 生成随机名称
		String fileName = UUIDUtils.getUUID(16) + suffix;

		mFilesUrlJSON.put("http_url", saveUploadFileVirtualUrl(POST, staticAccessPath) + fileName);
		mFilesUrlJSON.put("file_name", fileName);
		mFilesUrlJSON.put("server_url", saveUploadFileVirtualUrl(POST, staticAccessPath));
		mFilesUrlJSON.put("path", "/" + filePath + fileName);// 存储的目录
		mFilesUrlJSON.put("file_size", fileSize);
		mFilesUrlJSON.put("suffix", suffix);
		mFilesUrlJSON.put("old_file_name", oldFileName);
		File newFile = new File(uploadFolder + filePath, fileName);
		
		try {
			file.transferTo(newFile);
		} catch (Exception e) {
			errStr = e.getMessage();
			ILogUtil.info(e.getMessage());
			return false;
		}
		
		return true;
	}
	
	/**
	 * Description: 获取服务器地址,拼接虚拟路径
	 * @return
	 */
	private String saveUploadFileVirtualUrl(String POST, String staticAccessPath) {
        //获取本机IP
        String host = null;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        	ILogUtil.error("get server host Exception e:", e);
        }
        String virtual_url = host + ":" + POST + staticAccessPath.substring(0, staticAccessPath.length()-2);
        return virtual_url;
    }

	private boolean checkFile(String fileName, String filesType) {
		// 获取文件后缀
		if (filesType == null) {
			// 不校验
			return true;
		}
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		if (filesType.contains(suffix.trim().toLowerCase())) {
			return true;
		}
		return false;
	}


	private Object getParamsJson() {
		return (JSONObject) JSONObject.toJSON(params);
	}

	private JSONObject getFilesUrlJson() {
		return JSONObject.parseObject(JSON.toJSONString(mFilesUrlJSON));
	}

	private String getErrStr() {
		return errStr;
	}
	
	public static String RetResponse(int code, String msg) {
		JSONObject obj = new JSONObject();
		obj.put("code", code);
		obj.put("msg", msg);
		return obj.toString();
	}

	

}

最后是生成随机数的工具类

import java.util.UUID;

public class UUIDUtils {

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String getUUID(Integer len) {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
	}
}

用postman进行测试

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的Socket类来实现检测IP和端口的连通性。以下是一个简单的实现方法: ```java @Component public class ConnectionUtil { public boolean isAvailable(String ip, int port) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(ip, port), 1000); return true; } catch (IOException e) { return false; } } } ``` 这个工具类中,我们使用了Java的Socket类来创建一个Socket实例,并且使用connect()方法来连接指定的IP和端口。如果连接成功,返回true;如果连接失败,则返回false。 在Spring Boot中,我们可以使用@Value注解来获取配置文件中的IP和端口号,并且在Controller中调用ConnectionUtil的isAvailable()方法来检测连接是否可用: ```java @RestController public class ConnectionController { @Value("${ip}") private String ip; @Value("${port}") private int port; @Autowired private ConnectionUtil connectionUtil; @GetMapping("/check") public String checkConnection() { if (connectionUtil.isAvailable(ip, port)) { return "Connection is available."; } else { return "Connection is not available."; } } } ``` 在这个Controller中,我们使用了@GetMapping注解来指定HTTP请求的方法和路径,然后在checkConnection()方法中调用ConnectionUtil的isAvailable()方法来检测连接是否可用。如果可用,返回“Connection is available.”;如果不可用,返回“Connection is not available.”。 最后,在配置文件中添加IP和端口的配置: ``` ip=127.0.0.1 port=8080 ``` 这样,当我们访问http://localhost:8080/check时,就会检测IP和端口的连通性,并返回相应的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值