如何使用servlet将图像上传到指定的项目文件夹?

时间:2014-03-17 10:14:15

标签: jsp servlets file-upload

<body>
    <form method="POST" action="FileUpload" enctype="multipart/form-data" >
        File:
        <input type="file" name="fileSrc"  > <br/>
        <input type="submit" value="Upload" name="upload" >
    </form>
</body>

这是我的UploadImg.jsp,当我点击上传它进入FileUpload.java,其中上传的图像必须存储在我指定的文件夹AppImages中,我该怎么做?谢谢你的帮助。

1 个答案:

答案 0 :(得分:5)

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
             maxFileSize=1024*1024*10,      // 10MB
             maxRequestSize=1024*1024*50)

public class FileUploadServlet extends HttpServlet {
private static final String SAVE_DIR="images";

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ClassNotFoundException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
        String savePath = "C:" + File.separator + SAVE_DIR; //specify your path here
            File fileSaveDir=new File(savePath);
            if(!fileSaveDir.exists()){
                fileSaveDir.mkdir();
            }

        Part part=request.getPart("file");
        String fileName=extractFileName(part);
        part.write(savePath + File.separator + fileName);
       /* 
        //You need this loop if you submitted more than one file
        for (Part part : request.getParts()) {
        String fileName = extractFileName(part);
        part.write(savePath + File.separator + fileName);
    }*/
      //you can change this part acc. to your requirements
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/UploadFile","root","root");
        String query="INSERT INTO table_name(file) values (?)";

            PreparedStatement pst;
            pst=con.prepareStatement(query);

            String filePath= savePath + File.separator + fileName ;
            pst.setString(1,filePath);
            pst.executeUpdate();
}
// file name of the upload file is included in content-disposition header like this:
//form-data; name="dataFile"; filename="PHOTO.JPG"
private String extractFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) {
        if (s.trim().startsWith("filename")) {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
}
}

在这个servlet中,我们使用两个注释:           @WebServlet:标记此servlet,以便servlet容器在启动时加载它,并将其映射到URL模式/ FileUploadServlet。           @MultipartConfig:表示此servlet将处理多部分请求。我们将上传文件的最大大小限制为16 MB。

Source