Home Java javaTutorial Detailed explanation of using COS to implement file upload function in Java

Detailed explanation of using COS to implement file upload function in Java

May 18, 2018 pm 03:08 PM
java accomplish document

cos is an OpenSource component developed by O'Rrilly for HTTP upload files. Through this article, I will share with you how to use COS to implement the file upload function. Friends who are interested should take a look.

cos is an OpenSource component developed by O'Rrilly for HTTP file upload

Require cos.jar

Cos uploading files is very simple, simpler than fileupload: But I tried the maximum upload size, which is more than 800 megabytes. If it exceeds, it will crash directly:

java.io.IOException : Posted content length of 1627105576 exceeds limit of 889192448 --->byte, more than 800M

Just one servelt is enough:

package com.lhy.upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.FileRenamePolicy;
/**
 * CosServlet 
 * 在Cos中就一个类,
 * MultipartRequest它是request的包装类。
 */
@WebServlet(name="CosServlet",urlPatterns="/CosServlet")
public class CosServlet extends HttpServlet{
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  //第一步,声明文件的保存目录
  String path = getServletContext().getRealPath("/up");
  //第二步:文件上传
  //声明文件重新命名策略,默认的不行不能重命名,自己实现FileRenamePolicy接口
//  FileRenamePolicy rename = new DefaultFileRenamePolicy();
  MultipartRequest multiReq = new MultipartRequest(req, path, 1024*1024*100, "UTF-8",new MyRename());
  //输出所上传的文件的信息 
  Enumeration fileNames = multiReq.getFileNames(); 
  while(fileNames.hasMoreElements()){ 
    String name = (String)fileNames.nextElement(); 
    File file = multiReq.getFile(name);//得到上传的文件
    if(null != file){ 
      String fileName = multiReq.getFilesystemName(name);  //取得文件名 
      String contentType = multiReq.getContentType(name);//类型
      System.out.println("上传的文件: " +fileName+", 文件类型: "+contentType); 
    } 
  } 
  //输出所提交的表单中其它文本输入域的值 
  Enumeration formValue = multiReq.getParameterNames(); 
  while(formValue.hasMoreElements()){ 
    String param = (String)formValue.nextElement(); 
    String value = multiReq.getParameter(param); 
    System.out.println(value); 
  } 
  //第三步:如果知道input的name,还可以直接获取信息,
  /*resp.setContentType("text/html;charset=UTf-8");
  PrintWriter out = resp.getWriter();
  out.print("文件名称1:"+multiReq.getOriginalFileName("img1"));
  out.print("<br/>新名称:"+multiReq.getFilesystemName("img1"));
  out.print("<br/>类型1:"+multiReq.getContentType("img1"));
  out.print("<br/>大小1:"+multiReq.getFile("img1").length());
  out.print("<br/>说明:"+multiReq.getParameter("desc1"));
  if(multiReq.getContentType("img1").contains("image/")){
   out.print("<img width=&#39;300px&#39; height=&#39;200px&#39; src=&#39;"+req.getContextPath()+"/up/"+multiReq.getFilesystemName("img1")+"&#39;></img>");
  }
 out.print("<hr/>");
 out.print("文件名称2:"+multiReq.getOriginalFileName("img2"));
 out.print("<br/>类型2:"+multiReq.getContentType("img2"));
 out.print("<br/>大小2:"+multiReq.getFile("img2").length());
 out.print("<br/>说明2:"+multiReq.getParameter("desc2"));
// 
 out.print("<hr/>");
 out.print("文件名称3:"+multiReq.getOriginalFileName("img3"));
 out.print("<br/>类型3:"+multiReq.getContentType("img3"));
 out.print("<br/>大小3:"+multiReq.getFile("img3").length());
 out.print("<br/>说明3:"+multiReq.getParameter("desc3"));*/
 }
}
/**
 * 重命名策略,
 */
class MyRename implements FileRenamePolicy{
 @Override
 public File rename(File file) {
  String fileName = file.getName();
  String extName = fileName.substring(fileName.lastIndexOf("."));
  String uuid = UUID.randomUUID().toString().replace("-","");
  String newName = uuid+extName;//abc.jpg
  file = new File(file.getParent(),newName);
  return file;
 }
}
Copy after login

Form :

<form action="<c:url value=&#39;/CosServlet&#39;/>" method="post"
    enctype="multipart/form-data">
    File1:<input type="file" name="img1"><br /> 说明1:
    <input type="text" name="desc1"><br />
    File2:<input type="file" name="img2"><br/>
    说明2:<input type="text" name="desc2"><br/>
    File3:<input type="file" name="img3"><br/>
    说明3:<input type="text" name="desc3"><br/>
    <input type="submit" />
  </form>
Copy after login

Start uploading:

Server:

Summarize

The above is the detailed content of Detailed explanation of using COS to implement file upload function in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

See all articles