图片没有发生改变

图片没有发生改变

调试结束后,其他信息都能修改成功,但是图片还是原来的图片,没有删除也没有修改,请问老师是怎么回事?

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

18回答
好帮手慕柯南 2020-04-29 10:00:46

同学你好!

  1. 你的文件夹的名字改成upload了吗?

    http://img1.sycdn.imooc.com//climg/5ea8de5b09ad132003090099.jpg

  2. 你的路径中少了/导致路径出错

    http://img1.sycdn.imooc.com//climg/5ea8df530982566105150096.jpg

    正确示例:

    http://img1.sycdn.imooc.com//climg/5ea8df9c09e0457706450107.jpg

  3. 为了避免路径出错,建议你在以下位置使用绝对路径,比如:

    http://img1.sycdn.imooc.com//climg/5ea8dfc309f7997a07540137.jpg

祝学习愉快~

  • 提问者 学就完事儿 #1
    还是不行,我还是重新敲一次代码吧,麻烦老师了!感谢
    2020-04-29 13:29:41
  • 好帮手慕柯南 回复 提问者 学就完事儿 #2
    很抱歉,没有帮助到同学,这种问题一般都是路径问题,同学可以打断点查看一下执行过程中的路径和你实际的路径是否一样。 祝学习愉快~
    2020-04-29 15:54:45
提问者 学就完事儿 2020-04-28 20:36:14

PathUtil

public class PathUtil {

public static String seperator =System.getProperty("file.separator");

   public static String getImgBasePath() {

   String os = System.getProperty("os.name");

   String basePath="";

   if(os.toLowerCase().startsWith("win")) {

   basePath="/Intel/image/";

   }else {

   basePath="D:/Projectev/image/";

    }

   basePath=basePath.replace("/",seperator); 

   return basePath;

  }

   

   public static String getShopImagePath(long shopId) {

    String imagePath="upload/item/shop/"+shopId+"/";

    return imagePath.replace("/", seperator);

   }

}


好帮手慕柯南 2020-04-28 18:21:12

同学你好!

你代码中的路径是不是写错了呢,看你的图中Upload,一个大写一个小写。建议你将文件名字的首字母改成小写测试一下

http://img1.sycdn.imooc.com//climg/5ea8033d0918fce803870197.jpg

祝学习愉快~

  • 提问者 学就完事儿 #1
    还是不行啊老师.........
    2020-04-28 20:35:29
  • 提问者 学就完事儿 #2
    前端创建其他信息都OK , 但是图片信息就是找不到
    2020-04-28 20:40:35
提问者 学就完事儿 2020-04-28 17:28:48

其他信息都能添加,但是我的文件下路径下并没有图片http://img1.sycdn.imooc.com//climg/5ea7f7280928f5ea03610018.jpg


http://img1.sycdn.imooc.com//climg/5ea7f74c0900772607260279.jpg

好帮手慕柯南 2020-04-28 17:15:00

同学你好!

根据你的报错信息是代码的第128行报错了

http://img1.sycdn.imooc.com//climg/5ea7f34f0913941105830143.jpg

老师测试你的代码,发现你的用户名出的代码有误

http://img1.sycdn.imooc.com//climg/5ea7f3d50926ca0205740134.jpg

由于此时没有登录功能,所以相应的用户应该咱们手动写一下

http://img1.sycdn.imooc.com//climg/5ea7f401092d360c08120238.jpg

祝学习愉快~


提问者 学就完事儿 2020-04-28 16:05:30

http://img1.sycdn.imooc.com//climg/5ea7e3ab09c0f0df12300073.jpg

严重: Servlet.service() for servlet [spring-dispatcher] in context with path [/oyuan] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException

at com.imooc.oyuan.web.shopadmin.ShopManagementController.registerShop(ShopManagementController.java:128)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:567)

at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)

at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)

at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)

at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)

at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)

at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

at java.base/java.lang.Thread.run(Thread.java:835)


4月 28, 2020 3:59:07 下午 org.apache.catalina.core.StandardWrapperValve invoke

严重: Servlet.service() for servlet [spring-dispatcher] in context with path [/oyuan] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException

at com.imooc.oyuan.web.shopadmin.ShopManagementController.registerShop(ShopManagementController.java:128)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:567)

at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)

at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)

at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)

at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)

at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)

at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

at java.base/java.lang.Thread.run(Thread.java:835)


好帮手慕柯南 2020-04-28 15:28:29

同学你好!

你的意思是在页面修改时会出现问题吗?

http://img1.sycdn.imooc.com//climg/5ea7da2f0951355f11280614.jpg

你的js老师在本地又重新测试了一下,仍然是可以正常修改的。

会不会是同学的数据有问题呢?你可以检查一下在修改之前数据库中图片的地址,在相应的文件夹下是否存在。

也可以能是缓存导致的问题,建议重新编译一下项目,清除一下浏览器的缓存测试一下。

祝学习愉快~

  • 提问者 学就完事儿 #1
    还是不行,我重新试了下注册店铺报错了
    2020-04-28 16:04:23
  • 提问者 学就完事儿 #2
    我看了下文件,当时新增店铺时,文件并没有在路径下生成
    2020-04-28 16:06:27
提问者 学就完事儿 2020-04-28 15:02:08

老师您好,现在的问题是我在前端改不了图片

提问者 学就完事儿 2020-04-28 14:34:05
好帮手慕柯南 2020-04-28 14:33:58

同学你好!

很理解你的心情,但是老师这里测试你的代码的确是没有问题的呢,所以要一步一步来查找问题呢

请问你的本地以下代码执行了吗?

http://img1.sycdn.imooc.com//climg/5ea7cdb20987e11905480175.jpg

在执行以下删除代码时,路径是否是图片的路径呢?

http://img1.sycdn.imooc.com//climg/5ea7cde9098af93305590337.jpg

祝学习愉快~


  • 提问者 学就完事儿 #1
    在Service层测试的时候,已经测试成功了改变图片,但是在Contrllo层我在前端去缩略图的时候缺不会改变了
    2020-04-28 14:48:35
提问者 学就完事儿 2020-04-28 14:32:55

在控制台确实生成了新的图片,但是去文件夹还是没有改变图片啊

http://img1.sycdn.imooc.com//climg/5ea7cdf00942a80513200048.jpghttp://img1.sycdn.imooc.com//climg/5ea5348a0928247903360036.jpg

提问者 学就完事儿 2020-04-28 12:26:07

我重新测试了ShopService

又重新生成了一个新的图片但是我想改变图片就是不成功http://img1.sycdn.imooc.com//climg/5ea7b04e097b54d405220290.jpg

提问者 学就完事儿 2020-04-28 12:23:05

JS代码

$(function(){

var shopId = getQueryString('shopId');

var isEdit = shopId ? true : false;

var initUrl = '/oyuan/shopadmin/getshopinitinfo';

// 注册店铺的URL

var registerShopUrl ='/oyuan/shopadmin/registershop';

// 编辑店铺前需要获取店铺信息,这里为获取当前店铺信息的URL

var shopInfoUrl = "/oyuan/shopadmin/getshopbyid?shopId=" + shopId;

var editShopUrl = '/oyuan/shopadmin/modifyshop';

if(!isEdit){

getShopInitInfo();

}else{

getShopInfo(shopId);

}

function getShopInfo(shopId) {

$.getJSON(shopInfoUrl, function(data) {

if (data.success) {

// 若访问成功,则依据后台传递过来的店铺信息为表单元素赋值

var shop = data.shop;

$('#shop-name').val(shop.shopName);

$('#shop-addr').val(shop.shopAddr);

$('#shop-phone').val(shop.phone);

$('#shop-desc').val(shop.shopDesc);

// 给店铺类别选定原先的店铺类别值

var shopCategory = '<option data-id="'

+ shop.shopCategory.shopCategoryId + '" selected>'

+ shop.shopCategory.shopCategoryName + '</option>';

var tempAreaHtml = '';

// 初始化区域列表

data.areaList.map(function(item, index) {

tempAreaHtml += '<option data-id="' + item.areaId + '">'

+ item.areaName + '</option>';

});

$('#shop-category').html(shopCategory);

// 不允许选择店铺类别

$('#shop-category').attr('disabled', 'disabled');

$('#area').html(tempAreaHtml);

// 给店铺选定原先的所属的区域

$("#area option[data-id='" + shop.area.areaId + "']").attr(

"selected", "selected");

}

});

}

// 取得所有二级店铺类别以及区域信息,并分别赋值进类别列表以及区域列表


function getShopInitInfo(){

$.getJSON(initUrl,function(data){

if(data.success){

var tempHtml='';

var tempAreaHtml='';

data.shopCategoryList.map(function(item, index) {

tempHtml += '<option data-id="' + item.shopCategoryId

+ '">' + item.shopCategoryName + '</option>';

});

data.areaList.map(function(item, index) {

tempAreaHtml += '<option data-id="' + item.areaId + '">'

+ item.areaName + '</option>';

});

$('#shop-category').html(tempHtml);

$('#area').html(tempAreaHtml);

}

}); 

  }

$('#submit').click(function(){

var shop={};

if(isEdit){

shop.shopId=shopId;

}

shop.shopName=$('#shop-name').val();

shop.shopAddr=$('#shop-addr').val();

shop.phone=$('#shop-phone').val();

shop.shopDesc=$('#shop-desc').val();

shop.shopCategory = 

     {shopCategoryId : $('#shop-category').find('option').not(function() {

return !this.selected;

}).data('id')

};

shop.area = {

areaId : $('#area').find('option').not(function() {

return !this.selected;

}).data('id')

};// 获取上传的图片文件流

var shopImg = $('#shop-img')[0].files[0];

// 生成表单对象,用于接收参数并传递给后台

var formData = new FormData();

// 添加图片流进表单对象里

formData.append('shopImg', shopImg);

// 将shop json对象转成字符流保存至表单对象key为shopStr的的键值对里

formData.append('shopStr', JSON.stringify(shop));

var verifyCodeActual = $('#j_captcha').val();

if (!verifyCodeActual) {

$.toast('请输入验证码!');

return;

}

formData.append('verifyCodeActual', verifyCodeActual);

// 将数据提交至后台处理相关操作

$.ajax({

url :(isEdit?editShopUrl: registerShopUrl),

type : 'POST',

data : formData,

contentType : false,

processData : false,

cache : false,

success : function(data) {

if (data.success) {

$.toast('提交成功!');

}else{

$.toast('提交失败!'+data.errMsg);

}

$('#captcha_img').click();

}

});

});

})


好帮手慕柯南 2020-04-28 11:55:39

同学你好!

老师使用你的代码测试是没有任何问题的

http://img1.sycdn.imooc.com//climg/5ea7a8d509344a9312340628.jpg

同学打断点测试的时候,有在什么地方卡住吗?同学可以将自己测试的结果说明一下。

老师再帮同学排查一下问题。

祝学习愉快~

  • 提问者 学就完事儿 #1
    测试没有卡住啊
    2020-04-28 12:22:49
  • 提问者 学就完事儿 #2
    图片根本不会改变,麻烦老师帮看一下,找了好久
    2020-04-28 14:20:57
提问者 学就完事儿 2020-04-27 19:58:31

public class ImageUtil {

private static String basePath=Thread.currentThread().getContextClassLoader().getResource("").getPath();

private static final SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyMMddHHmmss");

private static final Random r= new Random();

private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

public static File transferCommonsMultipartFileToFile(CommonsMultipartFile cFile) {

File newFile = new File(cFile.getOriginalFilename());

try {

cFile.transferTo(newFile);

} catch (IllegalStateException e) {

logger.error(e.toString());

e.printStackTrace();

} catch (IOException e) {

logger.error(e.toString());

e.printStackTrace();

}

return newFile;

}

public static String generateThumbnail(InputStream thumbnailInputStream,String fileName,String targetAddr) {

// 获取不重复的随机名

String realFileName = getRandomFileName();

// 获取文件的扩展名如png,jpg等

String extension = getFileExtension(fileName);

// 如果目标路径不存在,则自动创建

makeDirPath(targetAddr);

// 获取文件存储的相对路径(带文件名)

String relativeAddr = targetAddr + realFileName + extension;

logger.debug("current relativeAddr is :" + relativeAddr);

// 获取文件要保存到的目标路径

File dest = new File(PathUtil.getImgBasePath() + relativeAddr);

logger.debug("current complete addr is :" + PathUtil.getImgBasePath() + relativeAddr);

try {

Thumbnails.of(thumbnailInputStream).size(200, 200)

.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)

.outputQuality(0.8f).toFile(dest);

} catch (IOException e) {

logger.error(e.toString());

                       e.printStackTrace();

}

return relativeAddr;

}

private static void makeDirPath(String targetAddr) {

// TODO Auto-generated method stub

String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;

File dirPath = new File(realFileParentPath);

if (!dirPath.exists()) {

dirPath.mkdirs();

}

}

private static String getFileExtension(String fileName) {

// TODO Auto-generated method stub

   return fileName.substring(fileName.lastIndexOf("."));

}

public static String getRandomFileName() {

// 获取随机的五位数

int rannum = r.nextInt(89999) + 10000;

String nowTimeStr = sDateFormat.format(new Date());

return nowTimeStr + rannum;

}

public static void main(String[] args) throws IOException {

String basePath=Thread.currentThread().getContextClassLoader().getResource("").getPath();

Thumbnails.of(new File("/Intel/image/xiaogou.jpg")).size(200, 200).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath+ "watermark.jpg")),

0.25f).outputQuality(0.8f).toFile("/Intel/image/xiaogounew.jpg");

 

}

/**

* storePath是文件的路径还是目录的路径, 如果storePath是文件路径则删除该文件,

* 如果storePath是目录路径则删除该目录下的所有文件

*

* @param storePath

*/

public static void deleteFileOrPath(String storePath) {

File fileOrPath = new File(PathUtil.getImgBasePath() + storePath);

if (fileOrPath.exists()) {

if (fileOrPath.isDirectory()) {

File files[] = fileOrPath.listFiles();

for (int i = 0; i < files.length; i++) {

files[i].delete();

}

}

fileOrPath.delete();

}

}

}


提问者 学就完事儿 2020-04-27 19:58:16

public class ShopServiceImpl implements ShopService {

@Autowired

private ShopDao shopDao;


@Transactional

public ShopExecution addShop(Shop shop, InputStream shopImgInputStream,String fileName) {

if (shop == null) {

            return new ShopExecution(ShopStateEnum.NULL_SHOP);

        }

try {

            // 给店铺信息赋初始值

            shop.setEnableStatus(0);

            shop.setCreateTime(new Date());

            shop.setLastEditTime(new Date());

            // 添加店铺信息

            int effectedNum = shopDao.insertShop(shop);

            if (effectedNum <= 0) {

                throw new ShopOperationException("店铺创建失败");

            } else {

                if (shopImgInputStream != null) {

                    // 存储图片

                    try {

                        addShopImg(shop, shopImgInputStream,fileName);

                    } catch (Exception e) {

                        throw new ShopOperationException("addShopImg error:" + e.getMessage());

                    }

                    // 更新店铺的图片地址

                    effectedNum = shopDao.updateShop(shop);

                    if (effectedNum <= 0) {

                        throw new ShopOperationException("更新图片地址失败");

                    }

                }

            }

        } catch (Exception e) {

            throw new ShopOperationException("addShop error:" + e.getMessage());

        }

return new ShopExecution(ShopStateEnum.CHECK,shop);

}


private void addShopImg(Shop shop, InputStream shopImgInputStream,String fileName) {

// TODO Auto-generated method stub

// 获取shop图片目录的相对值路径

        String dest = PathUtil.getShopImagePath(shop.getShopId());

        String shopImgAddr = ImageUtil.generateThumbnail(shopImgInputStream,fileName,dest);

        shop.setShopImg(shopImgAddr);

}



public Shop getByShopId(long shopId) {

return shopDao.queryByShopId(shopId);

}



public ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName)

throws ShopOperationException {

if (shop == null || shop.getShopId() == null) {

            return new ShopExecution(ShopStateEnum.NULL_SHOP);

        } else {

            // 1.判断是否需要处理图片

            try{

                if(shopImgInputStream != null && fileName != null && !"".equals(fileName)){

                    Shop tempShop = shopDao.queryByShopId(shop.getShopId());

                    if(tempShop.getShopImg() != null){

                        ImageUtil.deleteFileOrPath(tempShop.getShopImg());

                    }

                    addShopImg(shop, shopImgInputStream, fileName);

                }

                // 2.更新店铺信息

                shop.setLastEditTime(new Date());

                int effectedNum = shopDao.updateShop(shop);

                if (effectedNum <= 0) {

                    return new ShopExecution(ShopStateEnum.INNER_ERROR);

                } else {

                    shop = shopDao.queryByShopId(shop.getShopId());

                    return new ShopExecution(ShopStateEnum.SUCCESS, shop);

                }

            } catch (Exception e) {

                throw new ShopOperationException("modifyShop error:" + e.getMessage());

            }


        }

    }


}


提问者 学就完事儿 2020-04-27 19:57:58

@Controller

@RequestMapping("/shopadmin")

public class ShopManagementController {

@Autowired

private ShopService shopService;

@Autowired

private ShopCategoryService shopCategoryService;

  @Autowired

    private AreaService areaService;

  

  @RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)

    @ResponseBody

    private Map<String, Object> getShopById(HttpServletRequest request) {

        Map<String, Object> modelMap = new HashMap<String, Object>();

        Long shopId = HttpServletRequestUtil.getLong(request, "shopId");

        if (shopId > -1) {

            try {

                Shop shop = shopService.getByShopId(shopId);

                List<Area> areaList = areaService.getAreaList();

                modelMap.put("shop", shop);

                modelMap.put("areaList", areaList);

                modelMap.put("success", true);

            } catch (Exception e) {

                modelMap.put("success", false);

                modelMap.put("errMsg", e.toString());

            }

        } else {

            modelMap.put("success", false);

            modelMap.put("errMsg", "empty shopId");

        }

        return modelMap;

    }

  

  

    @RequestMapping(value="/getshopinitinfo",method = RequestMethod.GET)

    @ResponseBody

    private Map<String,Object> getShopInitInfo(){

        Map<String, Object> modelMap = new HashMap<String, Object>();

        List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();

        List<Area> areaList = new ArrayList<Area>();

        try {

            shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());

            areaList = areaService.getAreaList();

            modelMap.put("shopCategoryList", shopCategoryList);

            modelMap.put("areaList", areaList);

            modelMap.put("success", true);

        } catch (Exception e) {

            modelMap.put("success", false);

            modelMap.put("errMsg", e.getMessage());

        }

        return modelMap;

    }

  

@RequestMapping(value="/registershop",method=RequestMethod.POST)

@ResponseBody 

private Map<String, Object> registerShop(HttpServletRequest request){

  Map<String, Object> modelMap = new HashMap<String, Object>();

  if (!CodeUtil.checkVerifyCode(request)) {

            modelMap.put("success", false);

            modelMap.put("errMsg", "输入了错误的验证码");

            return modelMap;

        } 

//接受并转化相应的参数,包括店铺信息以及图片信息

  String shopStr=HttpServletRequestUtil.getString(request, "shopStr");

  ObjectMapper mapper=new ObjectMapper();

  Shop shop=null;

  try {

  shop=mapper.readValue(shopStr,Shop.class);

  }catch(Exception e){

  modelMap.put("success",false);

  modelMap.put("errMsg",e.getMessage());

  return modelMap;

  }

   CommonsMultipartFile shopImg = null;

        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(

                request.getSession().getServletContext());

        if (commonsMultipartResolver.isMultipart(request)) {

            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");

        } else {

            modelMap.put("success", false);

            modelMap.put("errMsg", "上传图片不能为空");

            return modelMap;

        }

//注册店铺

        if (shop != null && shopImg != null) {

            PersonInfo owner =(PersonInfo) request.getSession().getAttribute("user");

            shop.setOwner(owner);

            ShopExecution se;

try {

se = shopService.addShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());

if(se.getState() == ShopStateEnum.CHECK.getState()){

                    modelMap.put("success",true);

                    @SuppressWarnings("unchecked")

List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shoplist");

                    if(shopList == null || shopList.size() == 0) {

                        shopList = new ArrayList<Shop>();

                    }

                    shopList.add(se.getShop());

                    request.getSession().setAttribute("shopList", shopList);

            }else {

            modelMap.put("success",false);

            modelMap.put("errMsg",se.getStateInfo());

            }

} catch (ShopOperationException e) {

  modelMap.put("success",false);

  modelMap.put("errMsg",e.getMessage());

} catch (IOException e) {

  modelMap.put("success",false);

  modelMap.put("errMsg",e.getMessage());

}

            return modelMap;

        }else {

        modelMap.put("success", false);

         modelMap.put("errMsg", "请输出店铺信息");

         return modelMap;

        }

}

@RequestMapping(value = "/modifyshop",method = RequestMethod.POST)

    @ResponseBody

    private Map<String, Object> modifyshop(HttpServletRequest request) {

        Map<String, Object> modelMap = new HashMap<String, Object>();

        if (!CodeUtil.checkVerifyCode(request)) {

            modelMap.put("success", false);

            modelMap.put("errMsg", "输入了错误的验证码");

            return modelMap;

        }

        // 1.接收并转化相应的参数,包括店铺信息以及图片信息

        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");

        ObjectMapper mapper = new ObjectMapper();

        Shop shop = null;

        try {

            shop = mapper.readValue(shopStr, Shop.class);

        } catch (Exception e) {

            modelMap.put("success", false);

            modelMap.put("errMsg", e.getMessage());

            return modelMap;

        }

        CommonsMultipartFile shopImg = null;

        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(

                request.getSession().getServletContext());

        if (commonsMultipartResolver.isMultipart(request)) {

            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");

        }

        // 2.修改店铺信息

        if (shop != null && shop.getShopId() != null) {

            ShopExecution se;

            try {

                if(shopImg == null){

                    se = shopService.modifyShop(shop, null, null);

                }else{

                    se = shopService.modifyShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());

                }

                if(se.getState() == ShopStateEnum.SUCCESS.getState()){

                    modelMap.put("success",true);

                }else{

                    modelMap.put("success", false);

                    modelMap.put("errMsg", se.getStateInfo());

                }

            } catch (ShopOperationException e){

                modelMap.put("success", false);

                modelMap.put("errMsg", e.getMessage());

            } catch (IOException e) {

                modelMap.put("success", false);

                modelMap.put("errMsg", e.getMessage());

            }

            return modelMap;

        } else {

            modelMap.put("success", false);

            modelMap.put("errMsg", "请输入店铺Id");

            return modelMap;

        }

    }

/*

* private static void inputStreamToFile(InputStream ins,File file) {

* FileOutputStream os=null; try { os=new FileOutputStream(file); int

* bytesRead=0; byte[] buffer=new byte[1024];

* while((bytesRead=ins.read(buffer))!=-1) { os.write(buffer,0,bytesRead); }

* }catch(Exception e) { throw new

* RuntimeException("调用inputStreamToFile产生异常"+e.getMessage()); }finally { try {

* if(os!=null) { os.close(); } if(ins!=null) { ins.close(); }

* }catch(IOException e) { throw new

* RuntimeException("inputStreamToFile关闭io产生异常"+e.getMessage()); } } }

*/


}


好帮手慕柯南 2020-04-27 19:06:13

同学你好!

  1. 首先如果修改了图片,数据库中的图片路径会改变,相应的文件夹会新增新上传的图片,但是原来的图片是不会被删除的。

  2. 如果你的图片没有改变,应该是你的关于图片的逻辑错误了,建议你打断点跟踪一个后台的数据,看一下图片上传那里出错了。

如果不能找到问题可以继续提问

祝学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师