jsp/servlet上传文件

package controller;

import domain.File;
import jdbc.FileJdbc;
import jdbc.ServerJdbc;

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;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * Created by Solitude on 2017-6-13.
 */
@WebServlet("/fileController")
@MultipartConfig
public class FileController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String type = req.getParameter("type");
        int serverId = Integer.parseInt(req.getParameter("serverId"));
        String rootPath = "C:\\Users\\dell\\IdeaProjects\\myweb\\web\\WEB-INF\\settingfiles";
        if ("upload".equals(type)) {
            try {
                Part part = req.getPart("uploadFile");
                //获取请求的信息
                String name = part.getHeader("content-disposition");
                System.out.println(name);
//                String value1 = part.getName();
                String fileName = new String(part.getSubmittedFileName().getBytes("GBK"), "UTF-8");
//                System.out.println(value1 + " " + fileName);
//            String rootPath = req.getServletContext().getRealPath("settingfiles");获得的是部署后的路径
//                String rootPath = "C:\\Users\\dell\\IdeaProjects\\myweb\\web\\WEB-INF\\settingfiles";
                System.out.println("测试上传文件的路径:" + rootPath);
//        获得文件名后缀
                String fileSuffix = name.substring(name.lastIndexOf("."), name.length() - 1);
                System.out.println("测试获取文件的后缀:" + fileSuffix);
                //生成一个新的文件名,不重复,数据库存储的就是这个文件名,不重复的
                String fileSaveName = UUID.randomUUID().toString();
                String filename = rootPath + "\\" + fileSaveName + fileSuffix;
                System.out.println("测试产生新的文件名:" + filename);
                part.write(filename);
//                把文件信息存到数据库
                File file = new File(fileName, fileSuffix, fileSaveName);
                FileJdbc.insertAFile(file);
//                get file id
                int id = FileJdbc.getFileIdByFileSaveName(fileSaveName);
//                set server's settingFileId
                ServerJdbc.updateSettingFileId(id, serverId);
                PrintWriter out = resp.getWriter();
                out.println("上传成功!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String type = req.getParameter("type");
        int serverId = Integer.parseInt(req.getParameter("serverId"));
        String rootPath = "C:\\Users\\dell\\IdeaProjects\\myweb\\web\\WEB-INF\\settingfiles\\";
        if ("download".equals(type)) {
//            download file
//            get settingFileid
            int settingFileId = ServerJdbc.getSettingFileId(serverId);
            System.out.println(settingFileId);
            File file = FileJdbc.getFileById(settingFileId);
            String absolutePath = rootPath + file.getFileSaveName() + file.getFileSuffix();
            String realFileName = file.getFileName() + file.getFileSuffix();
            InputStream inputStream = new FileInputStream(absolutePath);
            //设置相应类型application/octet-stream
            System.out.println(absolutePath + " " + realFileName);
            //resp.setContentType("application/x-msdownload");
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName, "UTF-8"));
            OutputStream outputStream = resp.getOutputStream();
            System.out.println(absolutePath);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
            outputStream.close();
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSP中使用Servlet来处理文件上传是一种常见的做法。以下是一个简单的示例代码: 1. 创建一个JSP页面(upload.jsp),用于显示文件上传表单: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <h2>文件上传</h2> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="submit" value="上传"> </form> </body> </html> ``` 2. 创建一个Servlet(UploadServlet),用于处理文件上传请求: ```java import java.io.File; import java.io.IOException; 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("/upload") @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50) // 50MB public class UploadServlet extends HttpServlet { private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadPath = applicationPath + File.separator + UPLOAD_DIR; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } Part filePart = request.getPart("file"); String fileName = getFileName(filePart); String filePath = uploadPath + File.separator + fileName; filePart.write(filePath); response.getWriter().println("文件上传成功"); } private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); String[] elements = contentDisposition.split(";"); for (String element : elements) { if (element.trim().startsWith("filename")) { return element.substring(element.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } } ``` 在上述代码中,使用了`@MultipartConfig`注解来指定文件上传相关的配置,包括文件大小阈值、最大文件大小和最大请求大小。在`doPost`方法中,通过`request.getPart("file")`获取文件的`Part`对象,然后使用`write`方法将文件保存到指定的路径。 3. 部署应用程序到支持Servlet的容器中(如Tomcat),然后访问upload.jsp页面即可看到文件上传表单。 这是一个简单的文件上传示例,你可以根据实际需求进行修改和扩展。同时,请确保在实际开发中处理上传文件时要进行适当的安全验证和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值