問題描述
我有一個 jsp 表單,它接受有關(guān)員工姓名、性別、年齡、電子郵件地址和
I have a jsp form that accepts details about Employee name, sex, age, E-mail address and a
推薦答案
Servlet 3.0 container's 標(biāo)準(zhǔn)支持多部分?jǐn)?shù)據(jù).首先,您應(yīng)該編寫一個 HTML 頁面,該頁面接受文件輸入以及其他輸入?yún)?shù).
Servlet 3.0 container's has standard support for multipart data. First you should be writing a HTML page which takes the file input along with other input parameters.
<form action="uploadservlet" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="photo" />
<input type="submit" />
</form>
現(xiàn)在編寫一個使用 Servlet 3.0 Upload API 的 UploadServlet.這是演示 API 用法的代碼.首先,處理多部分?jǐn)?shù)據(jù)的 servlet 應(yīng)該使用以下兩種方法中的任何一種來定義 MultiPartConfig:
Now write a UploadServlet which uses the Servlet 3.0 Upload API. Here is the code which demonstrates the usage of API. Fist the servlet handling multipart data should define MultiPartConfig using any of the two approaches:
@MultiPartConfig
Servlet 類上的注解- 在
web.xml 中,
通過在<servlet>
定義中添加
條目.
@MultiPartConfig
annotation on Servlet Class- In
web.xml,
by adding<multipart-config>
entry inside<servlet>
definition.
這里是 UploadServlet,
Here is the UploadServlet,
@MultipartConfig
public class UploadServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse responst) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
if (parts.size() != 3) {
//can write error page saying all details are not entered
}
Part filePart = httpServletRequest.getPart("photo");
InputStream imageInputStream = filePart.getInputStream();
//read imageInputStream
filePart.write("somefiepath");
//can also write the photo to local storage
//Read Name, String Type
Part namePart = request.getPart("name");
if(namePart.getSize() > 20){
//write name cannot exceed 20 chars
}
//use nameInputStream if required
InputStream nameInputStream = namePart.getInputStream();
//name , String type can also obtained using Request parameter
String nameParameter = request.getParameter("name");
//Similialrly can read age properties
Part agePart = request.getPart("age");
int ageParameter = Integer.parseInt(request.getParameter("age"));
}
}
如果您沒有使用 Sevlet 3.0 Container,您應(yīng)該使用 Apache Commons File Upload.以下是使用 Apache Commons File Upload 的鏈接:
If you are not using Sevlet 3.0 Container, you should be truing Apache Commons File Upload. Here are the links for using Apache Commons File Upload:
- 使用 Apache Commons 文件上傳
- Apache Commons 文件上傳示例
參考資料:
- Servlet 3.0 javax.servlet.http.HttpServletRequest API
- Servlet 3.0 javax.servlet.http.Part API
- 使用 Servlet 3.0 上傳文件
這篇關(guān)于Java Servlet/Jsp 圖像與表單值一起上傳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!