Java:将图像保存在一个特定目录中

时间:2012-10-10 16:09:58

标签: java image-uploading

我在网上发现了这个servlet java,它从2级的xmlHttpRequest上传了一个图像。 现在,在servlet中我拥有了我需要的所有特征的图像对象:名称,大小,尺寸,ecc ...... 现在我想将图像存储在服务器的目录中。我该怎么办?

servlet的代码如下(不是我的):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String ajaxUpdateResult = "";

    try {

        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);            
        for (FileItem item : items) {
            if (item.isFormField()) {
                ajaxUpdateResult += "Field " + item.getFieldName() + 
                " with value: " + item.getString() + " is successfully read\n\r";
            } else {
                String fileName = item.getName();
                InputStream content = item.getInputStream();
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");

                // Do whatever with the content InputStream.

                System.out.println(item.getSize());

                //System.out.println(Streams.asString(content));
                ajaxUpdateResult += "File " + fileName + " is successfully uploaded\n\r";
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Parsing file upload failed.", e);
    }
    response.getWriter().print(ajaxUpdateResult);
}

2 个答案:

答案 0 :(得分:0)

只需尝试一下......

try {
    // retrieve image
    BufferedImage bi = getMyImage();
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    ...
}

请参阅此链接:

http://www.mkyong.com/java/how-to-write-an-image-to-file-imageio/

///////////////////////编辑部分/////////////////// //

两种方法

1。HTTP-POSTmultiparted文件一起使用,需要Apaches commons个库

public String postDataCreation(final String url, final String xmlQuery,final String path){

        final StringBuilder sa  = new StringBuilder();

        final File file1 = new File(path);




        Thread t2 = new Thread(new Runnable(){


            public void run() {

                try
                {
                     HttpClient client = MySSLSocketFactory.getNewHttpClient();
                     HttpPost post = new HttpPost(url);
                     FileBody bin1 = new FileBody(file1);

                     MultipartEntity reqEntity = new MultipartEntity();

                     reqEntity.addPart("dish_photo", bin1);

                     reqEntity.addPart("xml", new StringBody(xmlQuery));

                     post.setEntity(reqEntity);

                     HttpResponse response = client.execute(post);

                     HttpEntity entity = response.getEntity();
                        InputStream i = entity.getContent();

                        Log.d("Vivek", i.toString());
                        InputStreamReader isr = new InputStreamReader(i);

                        BufferedReader br = new BufferedReader(isr);

                        String s = null;


                        while ((s = br.readLine()) != null) {

                            Log.d("YumZing", s);
                            sa.append(s);
                        }






                }
                catch (Exception ex){

                }

            }





        });

        t2.start();

        try {
            t2.join();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

        System.out.println("Getting from Post Data Method "+sa.toString());
        return sa.toString();
    }

2。使用FTP上传,使用Apaches commons

    public void goforIt(){


            FTPClient con = null;

            try
            {
                con = new FTPClient();
                con.connect("xx.xx.xx.xx");

                if (con.login("Administrator", "361wl-sin"))
                {
                    con.enterLocalPassiveMode(); // important!
                    con.setFileType(FTP.BINARY_FILE_TYPE);
                    String data = "/sdcard/prerakm4a.m4a";
                    //ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
                    FileInputStream in = new FileInputStream(new File(data));
                    boolean result = con.storeFile("/prerakm4a.m4a", in);
                    in.close();
                    if (result) System.out.println("upload result"+" succeeded");
                    con.logout();
                    con.disconnect();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
  }

答案 1 :(得分:0)

try {
// retrieve image
BufferedImage bi = ImageIO.read(content);
File outputfile = new File(fileName);
ImageIO.write(bi, "png", outputfile);
} catch (Exception e) {
e.printStackTrace();
}