繁体   English   中英

用Spring MVC上传文件

[英]file upload with spring MVC

我正在使用Spring MVC和jquery上传文件。 在我的课堂方法中,我写了

    @RequestMapping(value="attachFile", method=RequestMethod.POST)
public @ResponseBody List<FileAttachment> upload(
        @RequestParam("file") MultipartFile file,
        HttpServletRequest request,
        HttpSession session) {
    String fileName =  null;
    InputStream inputStream = null;
    OutputStream outputStream = null;


    //Save the file to a temporary location 

    ServletContext context = session.getServletContext();
    String realContextPath = context.getRealPath("/");

    fileName =  realContextPath +"/images/"+file.getOriginalFilename();


    //File dest = new File(fileName);

    try {

        //file.transferTo(dest);

        inputStream = file.getInputStream();
        outputStream = new FileOutputStream(fileName);



        inputStream.close();
        outputStream.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我正在正确上传文件

   ServletContext context = session.getServletContext();
   String realContextPath = context.getRealPath("/");

获得路径。 我的第一个问题是,这是获取路径的正确方法吗,它将文件存储在工作区/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images的某个位置

当我尝试使用以下代码在我的jsp页面上显示此图像时

<img src="<%=request.getRealPath("/") + "images/images.jpg" %>" alt="Upload Image" />

它不显示图像,其生成以下html

 <img src="/home/name/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images/images.jpg" alt="Upload Image">

我做对了吗? 在我的项目中,我每天必须上传大量文件。

如果您还需要其他任何信息来理解我的问题,请告诉我

如果您通过绝对路径(例如C:\\images\\ )而不是相对路径(您的方法)将文件上传到某个目录中会更好。 通常,Web应用程序在生产环境的Linux Mathines上运行,并且使保存路径可配置是一个好习惯。

创建一些应用程序属性,该属性将保存文件的保存路径(在xml或属性文件中)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM