使用spring MVC上传文件

时间:2012-08-22 15:46:33

标签: java jquery 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的/图像

当我尝试使用以下代码在我的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">

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

如果您还有其他需要了解我的问题,请告诉我

1 个答案:

答案 0 :(得分:1)

如果您通过绝对路径(例如C:\images\)而不是相对(您的方法)上传某些目录中的文件会更好。通常,网络应用程序在生产中使用linux数学运行,并且最好使保存路径可配置。

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