Harry
Harry

Reputation: 4773

file upload with spring MVC

I am uploading file using spring MVC and jquery. Inside my class method I have written

    @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();
    }

Its uploading the file correctly I am using

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

to get the path. My first question is , Is this the correct way to get the path and it stores the file somewhere at workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/myproject/images

and when I am trying to display this image on my jsp page using the following code

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

It does not display the image, Its generating the following html

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

Am I doing the things right? In my project I have to upload large number of files everyday.

Please let me know if you need anything else to understand my question

Upvotes: 1

Views: 3615

Answers (1)

vacuum
vacuum

Reputation: 2273

It will be better if you upload your files in some directory by absolute path(e.g. C:\images\) instead of relative (your approach). Usually, web apps runs on linux mathines on production and it is good practice to make save path configurable.

Create some application property which will holds save path for files(in xml or property file).

Upvotes: 1

Related Questions