Springboot中的图片上传

前端jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title




后台1(没有使用绝对路径,即报错中有at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:122))

@RestController
public class FileController {
    @RequestMapping("/savefile")
    public String saveArea(@RequestParam("file") MultipartFile file) {
        String path = "D:\\safedistrict-img";
        String url = "";//返回存储路径
        if (file != null) {
            String fileName = file.getOriginalFilename();
            File targetFile = new File(fileName);
            if (!targetFile.isDirectory()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            url = path + fileName;
        }
        return url;
    }
}
@SpringBootApplication
public class Text1Application {

    public static void main(String[] args) {
        SpringApplication.run(Text1Application.class, args);
    }
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation("D:\\safedistrict-img");
        return factory.createMultipartConfig();
    }
}

后台2(服务器中)

 @RequestMapping("/savefile")
    public String saveArea(@RequestParam("file") MultipartFile file) {
        String path = ElantripConstants.UPLOAD_PATH;
        String url = null;
        if (file != null) {
            String fileName = file.getOriginalFilename();
            File targetFile = new File(path, fileName);
            if (!targetFile.isDirectory()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                rsInfo.setMessage("上传图片出错!!");
                rsInfo.setCode("23333");
            }
            url = ElantripConstants.UPLOAD_URL + fileName;
        }
    }
public class ElantripConstants {
	public static final String UPLOAD_PATH = "/usr/share/nginx/html/www/safedistrict-upload/";
	public static final String UPLOAD_URL = "http://www.emoonbow.com/safedistrict/"; // 服务器的访问地址
	public static final String QIUNIU_UPLOAD_URL = "http://youpaiyun.zaiyoyo.com/"; // 七牛云地址
}

你可能感兴趣的:(java功能片段)