怎样用servlet实现文件上传

 我来答
禅物离影巴0y
2016-12-04 · 贡献了超过254个回答
知道小有建树答主
回答量:254
采纳率:0%
帮助的人:25.8万
展开全部
编写上传页面,在WebContent目录下创建一个NewFile.jsp文件,并编写如下代码。注意: 必须加上 enctype="multipart/form-data" .表示以二进制的数据格式来传输。

开发处理文件上传的Servlet
 1、使用注解@MultipartConfig将一个Servlet标识为支持文件上传。
 2、Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。

将控制台打印的文件上传地址复制到地址栏。查看上传的文件,页面提示上传成功!

在编写servlet时,应该注意 必须注解 @MultipartConfig 将一个Servlet标识为支持文件上传,否则会导致上传失败。还有就是JSP页面上 form表单中 ,必须加上 enctype="multipart/form-data" .表示以二进制的数据格式来传输。

文件上传servlet类的代码编写。dopost()方法中的主要代码:(读者可参考注释自行进行编写,然后按照以上步骤进行测试)。
request.setCharacterEncoding("utf-8"); //获取文件部件part Part part=request.getPart("filename"); //获取服务器的路径 即上传路径 String root=request.getServletContext().getRealPath("/file"); //获取上传文件的头部信息 String headname=part.getHeader("content-disposition"); //获取文件后缀名 String ext = headname.substring(headname.lastIndexOf("."), headname.length()-1); // 上传目的地完整的路径 String filename=root+"/"+UUID.randomUUID().toString()+ext; System.out.println(filename); //导入文件 part.write(filename); request.setAttribute("info", "上传成功!"); request.getRequestDispatcher("/NewFile.jsp").forward(request, response); }
硪丨暧恋
2016-12-04 · TA获得超过8980个赞
知道大有可为答主
回答量:5336
采纳率:93%
帮助的人:2188万
展开全部
通过getInputStream()取得上传文件。

/**
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.individuals.web.servlet;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author Barudisshu
*/
@WebServlet(name = "UploadServlet", urlPatterns = {"/UploadServlet"})
public class UploadServlet extends HttpServlet {

/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//读取请求Body
byte[] body = readBody(request);
//取得所有Body内容的字符串表示
String textBody = new String(body, "ISO-8859-1");
//取得上传的文件名称
String fileName = getFileName(textBody);
//取得文件开始与结束位置
Position p = getFilePosition(request, textBody);
//输出至文件
writeTo(fileName, body, p);
}

//构造类
class Position {

int begin;
int end;

public Position(int begin, int end) {
this.begin = begin;
this.end = end;
}
}

private byte[] readBody(HttpServletRequest request) throws IOException {
//获取请求文本字节长度
int formDataLength = request.getContentLength();
//取得ServletInputStream输入流对象
DataInputStream dataStream = new DataInputStream(request.getInputStream());
byte body[] = new byte[formDataLength];
int totalBytes = 0;
while (totalBytes < formDataLength) {
int bytes = dataStream.read(body, totalBytes, formDataLength);
totalBytes += bytes;
}
return body;
}

private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {
//取得文件区段边界信息
String contentType = request.getContentType();
String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
//取得实际上传文件的气势与结束位置
int pos = textBody.indexOf("filename=\"");
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;

return new Position(begin, end);
}

private String getFileName(String requestBody) {
String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);
fileName = fileName.substring(0, fileName.indexOf("\n"));
fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));

return fileName;
}

private void writeTo(String fileName, byte[] body, Position p) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("e:/workspace/" + fileName);
fileOutputStream.write(body, p.begin, (p.end - p.begin));
fileOutputStream.flush();
fileOutputStream.close();
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式