我有一個Java類,它接受InputStream並對進入的數據進行編碼。如何獲得可接受來自用戶的文件上傳的工作,但將其視爲流而不是先保存整個磁盤並使用的FileInputStream?如何通過表單上傳文件並讓Java將其作爲InputStream處理?
基本上我正在尋找一些Java中的輕量級web框架,它只是讓我獲取用戶上傳的文件作爲數據流。
我有一個Java類,它接受InputStream並對進入的數據進行編碼。如何獲得可接受來自用戶的文件上傳的工作,但將其視爲流而不是先保存整個磁盤並使用的FileInputStream?如何通過表單上傳文件並讓Java將其作爲InputStream處理?
基本上我正在尋找一些Java中的輕量級web框架,它只是讓我獲取用戶上傳的文件作爲數據流。
如果尚未完成,請安裝一個webserver/servletcontainer,如Apache Tomcat。
如果您選擇Tomcat 6.x,然後使用Apache Commons FileUpload將上傳的文件作爲InputStream
。如果您選擇Tomcat 7.x(Servlet 3.0),然後使用HttpServletRequest#getPart()
,然後使用Part#getInputStream()
獲取上傳的文件,作爲InputStream
。
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileUpload extends HttpServlet {
private static final Logger log =
Logger.getLogger(FileUpload.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
// You now have the filename (item.getName() and the
// contents (which you can read from stream). Here we just
// print them back out to the servlet output stream, but you
// will probably want to do something more interesting (for
// example, wrap them in a Blob and commit them to the
// datastore).
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
res.getOutputStream().write(buffer, 0, len);
}
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
該示例是從Google App Engine文檔中提取的,因爲GAE也不允許應用程序在磁盤上寫入文件。原始示例可以發現here