关于common-fileupload的一些网络资料1
来源:互联网 发布:为什么淘宝点不开客服 编辑:程序博客网 时间:2024/05/29 19:44
首先要了解上传的本质,首先上传需要在jsp页面的form标签中配置enctype="multipart/form-data"
因为这样配置后,在http请求发出时才会以2进制的方式去传输上传文件
当请求到达服务端后,在action我们的代码是
- DiskFileItemFactory factory = new DiskFileItemFactory();
-
- factory.setSizeThreshold(300000);
-
- factory.setRepository(new File("D:<SPAN style="COLOR: #0000ff">//</SPAN>temp"));
- ServletFileUpload upload = new ServletFileUpload(factory);
-
- upload.setSizeMax(20000000);
在设定好了一系列参数后,我们就要开始主要的方法了
ServletFileUpload.parseRequest(Request request)
- public List parseRequest(HttpServletRequest request)
- throws FileUploadException {
- return parseRequest(new ServletRequestContext(request));
- }
public List /* FileItem */ parseRequest(HttpServletRequest request) throws FileUploadException { return parseRequest(new ServletRequestContext(request)); }
- public List parseRequest(RequestContext ctx)
- throws FileUploadException {
- try {
- FileItemIterator iter = getItemIterator(ctx);
- List items = new ArrayList();
- FileItemFactory fac = getFileItemFactory();
- if (fac == null) {
- throw new NullPointerException(
- "No FileItemFactory has been set.");
- }
- while (iter.hasNext()) {
- FileItemStream item = iter.next();
- FileItem fileItem = fac.createItem(item.getFieldName(),
- item.getContentType(), item.isFormField(),
- item.getName());
- try {
-
-
- Streams.copy(item.openStream(), fileItem.getOutputStream(),
- true);
- } catch (FileUploadIOException e) {
- throw (FileUploadException) e.getCause();
- } catch (IOException e) {
- throw new IOFileUploadException(
- "Processing of " + MULTIPART_FORM_DATA
- + " request failed. " + e.getMessage(), e);
- }
- if (fileItem instanceof FileItemHeadersSupport) {
- final FileItemHeaders fih = item.getHeaders();
- ((FileItemHeadersSupport) fileItem).setHeaders(fih);
- }
- items.add(fileItem);
- }
-
- return items;
- } catch (FileUploadIOException e) {
- throw (FileUploadException) e.getCause();
- } catch (IOException e) {
- throw new FileUploadException(e.getMessage(), e);
- }
- }
public List /* FileItem */ parseRequest(RequestContext ctx) throws FileUploadException { try { FileItemIterator iter = getItemIterator(ctx);//这个方法是相当重要的,在下面介绍 List items = new ArrayList(); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException( "No FileItemFactory has been set."); } while (iter.hasNext()) { FileItemStream item = iter.next(); FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName()); try {//将2个流copy,item.openStream()是request中的流,fileItem.getOutputStream()是准备向指定上传文件夹写文件的流//fileItem.getOutputStream() 中就设定了临时文件的路径 下面将介绍 Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } if (fileItem instanceof FileItemHeadersSupport) { final FileItemHeaders fih = item.getHeaders(); ((FileItemHeadersSupport) fileItem).setHeaders(fih); } items.add(fileItem); }//返回FileItem的集合(关于FileItem的实现类,大家可以参考DiskFileItem) return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } }
- public OutputStream getOutputStream()
- throws IOException {
- if (dfos == null) {
- File outputFile = getTempFile();
- dfos = new DeferredFileOutputStream(sizeThreshold, outputFile);
- }
- return dfos;
- }
-
- protected File getTempFile() {
-
- if (tempFile == null) {
- File tempDir = repository;
- if (tempDir == null) {
- tempDir = new File(System.getProperty("java.io.tmpdir"));
- }
-
- String tempFileName =
- "upload_" + UID + "_" + getUniqueId() + ".tmp";
-
- tempFile = new File(tempDir, tempFileName);
- }
- return tempFile;
- }
public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; } protected File getTempFile() { //如果没设置临时目录,就用System.getProperty("java.io.tmpdir") if (tempFile == null) { File tempDir = repository; if (tempDir == null) { tempDir = new File(System.getProperty("java.io.tmpdir")); } //设计临时文件名 String tempFileName = "upload_" + UID + "_" + getUniqueId() + ".tmp"; tempFile = new File(tempDir, tempFileName); } return tempFile; }
- public FileItemIterator getItemIterator(RequestContext ctx)
- throws FileUploadException, IOException {
- return new FileItemIteratorImpl(ctx);
- }
public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { return new FileItemIteratorImpl(ctx); }
- FileItemIteratorImpl(RequestContext ctx)
- throws FileUploadException, IOException {
- if (ctx == null) {
- throw new NullPointerException("ctx parameter");
- }
-
- String contentType = ctx.getContentType();
FileItemIteratorImpl(RequestContext ctx) throws FileUploadException, IOException { if (ctx == null) { throw new NullPointerException("ctx parameter"); } String contentType = ctx.getContentType();
-
-
- if ((null == contentType)
- || (!contentType.toLowerCase().startsWith(MULTIPART))) {
- throw new InvalidContentTypeException(
- "the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream, content type header is "+ contentType);
- }
-
- InputStream input = ctx.getInputStream();
-
-
- if (sizeMax >= 0) {
- int requestSize = ctx.getContentLength();
- if (requestSize == -1) {
- input = new LimitedInputStream(input, sizeMax) {
- protected void raiseError(long pSizeMax, long pCount)
- throws IOException {
- FileUploadException ex =
- new SizeLimitExceededException(
- "the request was rejected because" + " its size (" + pCount + ") exceeds the configured maximum" + " (" + pSizeMax + ")", pCount, pSizeMax);
- throw new FileUploadIOException(ex);
- }
- };
- } else {
-
- if (sizeMax >= 0 && requestSize > sizeMax) {
- throw new SizeLimitExceededException(
- "the request was rejected because its size ("
- + requestSize + ") exceeds the configured maximum ("+ sizeMax + ")", requestSize, sizeMax);
- }
- }
- }
当返回了这个FileItem集合后,我们的代码如下
- List<FileItem> items = getUploadFileIteams(request,pushObj,goUrl);
-
- for (FileItem item : items) {
- File file = new File(realPath);
- item.write(file);
- }
List<FileItem> items = getUploadFileIteams(request,pushObj,goUrl);for (FileItem item : items) {File file = new File(realPath);item.write(file);}
这里就将文件真正写到了服务器上
再最后把item.write这个方法贴下吧,大家就更明白了
- public void write(File file) throws Exception {
- if (isInMemory()) {
- FileOutputStream fout = null;
- try {
- fout = new FileOutputStream(file);
- fout.write(get());
- } finally {
- if (fout != null) {
- fout.close();
- }
- }
- } else {
- File outputFile = getStoreLocation();
- if (outputFile != null) {
-
- size = outputFile.length();
-
- if (!outputFile.renameTo(file)) {
- BufferedInputStream in = null;
- BufferedOutputStream out = null;
- try {
- in = new BufferedInputStream(
- new FileInputStream(outputFile));
- out = new BufferedOutputStream(
- new FileOutputStream(file));
- IOUtils.copy(in, out);
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
-
- }
- }
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
-
- }
- }
- }
- }
- } else {
-
-
-
-
- throw new FileUploadException(
- "Cannot write uploaded file to disk!");
- }
- }
- }