簡體   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