1

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("/");

パスを取得します。私の最初の質問は、これはパスを取得する正しい方法であり、workspace/.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">

私は正しいことをしていますか?私のプロジェクトでは、毎日多数のファイルをアップロードする必要があります。

私の質問を理解するために他に何か必要な場合はお知らせください

4

1 に答える 1

1

C:\images\相対パス(アプローチ)ではなく絶対パス(例)でファイルをディレクトリにアップロードするとよいでしょう。通常、Webアプリは本番環境のLinux mathinesで実行されるため、保存パスを構成可能にすることをお勧めします。

ファイルの保存パスを保持するアプリケーションプロパティを作成します(xmlまたはプロパティファイル)。

于 2012-08-22T15:55:01.697 に答える