上传图片成功,网页却加载不出来
问题描述:
代码运行正常,返回的结果也没问题,文件可以上传到本地,就是网页加载不了
server.port=8083 spring.datasource.name=imooc_mall_datasource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc_mall?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=root mybatis.mapper-locations=classpath:mappers/*.xml spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= icode=ABCDE file.upload.dir=E:/BaiduNetdiskDownload/imooc-mall/image/
package com.imooc.mall.config; import com.imooc.mall.common.Constant; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class ImoocMallWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("/image/**").addResourceLocations( "file:" + Constant.FILE_UPLOAD_DIR); registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); } }
@PostMapping("admin/upload/file") public ApiRestResponse upload(HttpServletRequest httpServletRequest ,@RequestParam("file") MultipartFile file){ String filename = file.getOriginalFilename(); String suffixName = filename.substring(filename.lastIndexOf(".")); //生成文件uuid UUID uuid = UUID.randomUUID(); String uuidSuffixName = uuid.toString() + suffixName; //创建文件 File fileDirectory = new File(Constant.FILE_UPLOAD_DIR); File targetFile = new File(Constant.FILE_UPLOAD_DIR +uuidSuffixName); if (!fileDirectory.exists()){ if (!fileDirectory.mkdir()){ return ApiRestResponse.error(ImoocMallExceptionEnum.MKDIR_FAILED); } } try { file.transferTo(targetFile); } catch (IOException e) { throw new RuntimeException(e); } try { return ApiRestResponse.success( getUri(new URI(httpServletRequest.getRequestURL() + "")) + "/image/" + targetFile); } catch (URISyntaxException e) { return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_FAILED); } } private URI getUri(URI uri){ URI effectUri; try { effectUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null , null); } catch (URISyntaxException e) { effectUri = null; } return effectUri; }
相关截图:
相关截图:
相关截图:
5
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星