springboot上传图片到本地磁盘,访问虚拟路径显示

目录

前言

一、配置虚拟路径

二、表单.jsp add界面-可预览图片

三、后端controller

四、table.jsp

总结


博主遇到的报错有:

Failed to load resource: the server responded with a status of 404 ()

Not allowed to load local resource

都解决了,可以看看以下代码。




前言

最近刚学了文件上传,实战springboot2实现文件上传到本地后用虚拟路径访问到图片

省略实体类,dao,service


提示:以下是本篇文章正文内容,下面案例可供参考



一、配置虚拟路径

1.application.properties中配置

#配置静态资源文件 我这里是d://temp1/
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/, 
classpath:/static/, classpath:/public/, file:d://temp1/

spring.servlet.multipart.max-file-size=5242880
spring.servlet.multipart.max-request-size=20MB

#这个是配置的虚拟路径,我这里没写
file.staticAccessPath=/**
#这个是访问的本地磁盘文件
file.uploadFolder=D:/temp1/

2. 创建配置类 

@Configuration
public class WebConfig implements WebMvcConfigurer {
	/**
	 * 配置静态访问资源
	 * 
	 * @param registry
	 */
	@Value("${file.staticAccessPath}")
	private String staticAccessPath;
	@Value("${file.uploadFolder}")
	private String uploadFolder;

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

	}



二、表单.jsp add界面-可预览图片

</script>
<script type="text/javascript">
	function xmTanUploadImg(obj) {
		var file = obj.files[0];
		console.log("obj:" + obj);
		console.log("file:" + file);
		console.log("fileName:" + file.name)
		console.log("file.size = " + file.size);
		var reader = new FileReader();
		reader.onload = function(e) {
			console.log(e)// ProgressEvent 对象,里面的target.result就是base64编码
			console.log("成功读取....");
			var img = document.getElementById("avarimgs");
			img.src = e.target.result;
			//或者 img.src = this.result;  //e.target == this
		}
		reader.readAsDataURL(file)
	}

	function reg() {
		let form = new FormData($("#form-data")[0])
		console.log(form)
		$.ajax({
			//接口地址
			url : 'submit',
			type : 'POST',
			data : form,
			async : false,
			cache : false,
			contentType : false,
			processData : false,
			success : function(data) {
				console.log(data)
				console.log(data.photo);
				sessionStorage.setItem("img_name", data.photo);
                //./details1通过controller查询全部内容后跳转到表格显示
				window.location.href = "./details1";
			}
		});
	}
</script>
</head>
<body>
	<div style="margin: 20px 0;"></div>

	<form id="form-data">
		<table>
			
			<tr>
				<td>id编号:</td>
				<td><input id="id" name="id"></td>
			</tr>
			<tr>
				<td>图书名称:</td>
				<td><input id="name" name="name"></td>
			</tr>
			<tr>
				<td>价格</td>
				<td><input id="price" name="price"></td>
			</tr>
			<tr>
				<input type="file" accept="*/*" name="file" id="FileImg"
					onchange="xmTanUploadImg(this)">
				<img src="" alt="默认头像地址(可以自己填)" id="avarimgs"
					style="border-radius: 50%" width="200px" height="200px">
			</tr>
			
			<tr>

				<td></td>
				<input type="button" value="注册" id="registerBtn" onclick="reg()">

			</tr>
		</table>
	</form>

</body>

 三、后端controller

@Controller
public class FileController {

	@Autowired
	sxy1913041301IBookService bservice;
	
	
	@Value("${file.uploadFolder}")
	private String uploadFolder;
	
	@PostMapping("/submit")
	@ResponseBody
	public Book submit(MultipartFile file, Book info,HttpServletRequest req) throws Exception {		
		//使用UUID生成唯一标识文件名
	    String randomNumber = UUID.randomUUID().toString().replace("-", "");
	    //获取文件的原始名
	    String oldFilename = file.getOriginalFilename();
	  //获取文件后缀 .pdf
	    String extension = oldFilename.substring(oldFilename.lastIndexOf("."));
	    //生成新的文件名
	    String newFileName = randomNumber + extension;

	    File dateDir = new File(uploadFolder);

	    if (!dateDir.exists()) {
	        //判断目录是否存在,不存在则直接创建
	        dateDir.mkdirs();
	    }
	    try {
	        file.transferTo(new File(dateDir, newFileName));
	    } catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
        //把图片的地址存到book的photo属性中
	    info.setPhoto(req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort() + "/" + newFileName);
		System.out.println(info);
		bservice.addBook(info);
		return info;
	}
}
@Controller

public class sxy1913041301Controller {
	
	@Autowired
	 sxy1913041301IBookService bservice;
	@Autowired
	 Book book;
	/**
	 * 添加信息页面
	 * @return
	 */
	@GetMapping("add")
	public String add() {
		return ("book/add2");
	}
	


	@RequestMapping("details1")
	public ModelAndView table() {
		List<Book> books = bservice.findBooks();
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/book/sxy1913041301table");
		mv.addObject("booksList", books);
		return mv;
	}
}

四、table.jsp

<c:forEach items="${booksList}" var="book">
						<tr>

							<td>${book.id}</td>
							<td>${book.name}</td>
							<td>${book.price}</td>
							<td><img src="${book.photo}"></td>
						</tr>
</c:forEach>



总结

博主由于太菜鸟了搜了很多很多帖子,借鉴融合了很多内容

欢迎大家一起讨论学习~

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值