2012-01-12 30 views

回答

2

您应该阅读有关Java servlet和servlet容器的内容。首先执行一个简单的servlet,返回“Hello world”字符串。

这里是最短的上传/下载的servlet永远

import org.apache.commons.io.IOUtils; 

@WebServlet(urlPatterns = {"/test"}) 
public class DownloadServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     File f = new File("test.txt"); 
     resp.setContentLength((int) f.length()); 
     final FileInputStream input = new FileInputStream(f); 
     IOUtils.copy(input, resp.getOutputStream()); 
     input.close(); 
    } 

    @Override 
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     final FileOutputStream output = new FileOutputStream("test.txt"); 
     IOUtils.copy(req.getInputStream(), output); 
     output.close(); 
    } 
} 

先打:

$ curl -X PUT -d "Hello, servlet" localhost:8080/test 

要存储在磁盘上的一个名为test.txt某个文件中给出的文本。然后在您的浏览器中输入localhost:8080/test。我认为这是一个好的开始。

+0

而我有一个字节的缓冲区?下一步是什么?我怎样才能将这个缓冲区转换成jpg文件并将其存储在硬盘中? – 2012-01-12 18:26:08

+0

@LeifEricson:看看我的编辑,有一个完整的例子。为什么downvote?与此同时,我正在研究[SSCCE](http://sscce.org/)... – 2012-01-12 18:40:14

相关问题