上传图片,Not allowed to load local resource,springboot上传

原文地址:https://blog.csdn.net/J_Cxn/article/details/78497354

最近朋友找我,帮她做一个招聘的网站的demo,本来是不想做的,谁让是一个美女呢,没办法, 程序猿嘛,看见美女就.嘻嘻.哦!扯远了,话不多说直接就上.

1.所需要pom依赖有:

<dependency>

<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>


<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>


<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>

</dependency>

2.前端代码
2.1 html 代码

<div class="layui-form-item">
<label class="layui-form-label">上传图片</label>
<div class="layui-input-block">
<div width="20%"></div>
<div width="80%" >
<img width="100" height="100" id="allUrl"/>
<input type="hidden" name="imgUrl" id="imgUrl"/>
<input id="uploadPic" type="file" name="pic" lay-filter="uploadPic"/>
</div> 
</div>
</div>

2.2 js代码

// 上传照片
$('#uploadPic').on('change', function() {
var a = $("#uploadPic").get(0).files[0];
if(a.size>1048576){
layer.msg("上传的图片过大,请处理后在上传....");
return;
}
var option = {
url : "../upload/uploadPic",
type : "post",
dataType : "json",
success : function(data) {
if(data.code!=1000){
layer.msg(data.msg);
}else{
// 对data操作
// 1、图片回显
$("#allUrl").attr("src", data.allUrl);
// 2、设置隐藏域的值
$("#imgUrl").val(data.imgUrl);
}
}
}
$("#jvForm").ajaxSubmit(option);//form表单提交, 如果没用就按照你自己的提交方式就行
})

3.java代码

/**
 * 
 * @author j_cxn
 * @description : [上传图片]
 *
 * @时间: 2017年11月10日 上午10:25:08
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

@RequestMapping("/uploadPic")
public void uploadPic(MultipartFile pic,HttpServletRequest request, HttpServletResponse response){
JSONObject jsonObject = new JSONObject();
try {
// 图片改名
String filename = pic.getOriginalFilename();
// 后缀   无"."
String suffix = FilenameUtils.getExtension(filename);
//uuid,给上传图片重新起名字
String uuid = UUID.randomUUID().toString().replace("-", "");
String newName = uuid + "." + suffix;
//照片大小
long size = pic.getSize();
if(size>=1048576){
jsonObject.put("msg", "图片过大");
jsonObject.put("code", 500); // 保存图片地址
}else{
String realPath = "D:\\imagesuuuu\\";
String imgUrl = realPath + newName; // 相对路径 ,这里没有图片服务器,所以就先放到本地, 如果有图片服务器就用图片服务器
// 上传
pic.transferTo(new File(imgUrl));

// 回显图片
jsonObject.put("allUrl", "../images/"+newName);
jsonObject.put("imgUrl", "../images/"+newName); // 保存图片地址
jsonObject.put("code", 1000); // 保存图片地址
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(jsonObject.toString());
}
} catch (Exception e) {//异常处理
try {
jsonObject.put("code", 500); // 保存图片地址
jsonObject.put("msg", "图片过大");
e.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
}

}

4.如果存放到本地的话, 回显图片的时候就会遇到问题Not allowed to load local resource

因为浏览器会保护,不允许家在本地,这就就的我们自己弄一个虚拟路径,查了一些资料找到了解决办法如下:

5.虚拟文件,将本地文件虚拟成系统文件

5.1java代码:

@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
// 获取配置文件中图片的路径
@Value("${cbs.imagesPath}")
private String mImagesPath;


// 访问图片方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")) {
String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
if (imagesPath.indexOf(".jar") > 0) {
imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
} else if (imagesPath.indexOf("classes") > 0) {
imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
}
imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
mImagesPath = imagesPath;
}
LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath=" + mImagesPath);
registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
super.addResourceHandlers(registry);
}

5.2application.properties文件

 cbs.imagesPath=file:/D:/imagesuuuu/

这样就将d盘中的imagesuuuu文件夹虚拟成本系统中的images,项目结构

                                                                                                               

6.效果展示

                                                   

图片位置不在系统中,而是在本地的D盘

git地址:https://github.com/MrCXN/parttime

如有问题请评论,会及时回复的.

猜你喜欢

转载自blog.csdn.net/tanga842428/article/details/82182070