Springmvc display problems after uploading pictures

Now I am learning the SSM framework and have done a file upload function. The code is referenced on www.how2j.com. Mainly as follows:
Write picture description here
1.web.xml

<!--允许访问jpg。 并且必须加在springmvc的servlet之前-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>

2.springmvc-servlet.xml

<!--开放对上传功能的支持-->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

3.upload.jsp upload page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>

<form action="uploadImage" method="post" enctype="multipart/form-data">
  选择图片:<input type="file" name="image" accept="image/*" /> <br> 
  <input type="submit" value="上传">
</form>

4.UploadedImageFile.java

package pojo;
 /**
 *封装MultipartFile类型的字段 image ,用于接受页面的注入
 *
 */
import org.springframework.web.multipart.MultipartFile;

public class UploadedImageFile {
    
    
    MultipartFile image;

    public MultipartFile getImage() {
        return image;
    }

    public void setImage(MultipartFile image) {
        this.image = image;
    }

}

5.UploadController uploads the controller.

package controller;
import java.util.*;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.xwork.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;


import pojo.UploadedImageFile;

@Controller
public class UploadController {
 /**
 *upload 映射上传路径/uploadImage
 * 方法的第二个参数UploadedImageFile 中已经注入好了 image
 *通过 RandomStringUtils.randomAlphanumeric(10);获取一个随机文件名。
 *根据request.getServletContext().getRealPath 获取到web目录下的image目录,用于存放上传后的文件。
 *调用file.getImage().transferTo(newFile); 复制文件
 *把生成的随机文件名提交给视图,用于后续的显示
 */
    @RequestMapping("/uploadImage")
    public ModelAndView upload(HttpServletRequest request,UploadedImageFile file)
            throws IllegalStateException, IOException {
        String name = RandomStringUtils.randomAlphanumeric(10);
        String newFileName = name + ".jpg";
        File newFile = new File(request.getServletContext().getRealPath("/image"), newFileName);
        newFile.getParentFile().mkdirs();
        file.getImage().transferTo(newFile);

        ModelAndView mav = new ModelAndView("showUploadedFile");
        mav.addObject("imageName", newFileName);
        //System.out.println(request.getServletContext().getRealPath("/image"));
        return mav;
    }
}

6.showUploadedFile.jsp shows the picture page

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

<img src="image/${imageName}"/>

When I practiced these codes, some problems appeared.
Write picture description here
The picture is not displayed, and I did not find the uploaded picture in my project, and reported a null pointer exception.
HTTP Status 500-Request processing failed; nested exception is java.lang.NullPointerException
Write picture description here
I began to wonder if there is a problem with the code. So I found a code for uploading pictures.

@RequestMapping("/uploadImage")
    public ModelAndView upload(HttpServletRequest request)
            throws IllegalStateException, IOException {
        String imgPath = null;
        //将当前上下文初始化给CommonsMultipartResolve(多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
             //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                //把上传路径写死
                    String path="E:/newWork/test/image/"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                    imgPath = file.getOriginalFilename();
                }    
            }   
        }
        ModelAndView mav  = new ModelAndView("showUpload");
        mav.addObject("imageName",imgPath);
        return mav;
    }

The upload of the file is successful, but the picture is still not displayed. Baidu took a look. The problem of not being able to access static resources is that it is the interception problem of springmvc. Trying a lot of solutions is useless. Later, I simply downloaded the source code and ran it again, and the pictures were displayed, but I still didn't see the uploaded pictures in my project, and http://:8080/test/uploadImage still had a null pointer abnormality. But since the image can be accessed, this file must exist, which means that the upload was successful. Where is the image? I will look at the code again and change request.getServletContext().getRealPath("/image" ) Print it out, and the
result is E:/NewWork/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/test/image (NewWork is my workspace)
What is this? I Baidu, when running the project by starting tomact, eclipse will publish the project to this folder, just like publishing to tomact. Maybe I set the server path to this folder by default when configuring tomact. You can modify it and change it to the webapps folder in the tomact installation directory. It might be easier to understand.
Write picture description here
Therefore, we know that the pictures accessed by the project must be found from the project files published in tomact. request.getServletContext().getRealPath("/image") is to find the path of the project in tomact. The successful picture is not displayed for the first time. It may be that the project published to tomact is not updated, so that the file content of the workspace is inconsistent with that in tomact.
The replaced code in the second paragraph is even less likely to access the picture, because I wrote the upload path to the project folder of the workspace, instead of the tomact server, which of course will not be found. Therefore, the path should not be hard-coded when uploading files. It is better to use request.getServletContext().getRealPath("/xxxxx").

Guess you like

Origin blog.csdn.net/sinat_35803474/article/details/82621791