Java servlet上传文件(照片视频)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Ani521smile/article/details/52016033

使用SmartUpload类上传
=============================================

 package com.suneasy.appaction;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.suneasy.web.dao.t_dao;
import com.suneasy.web.mod.app_add;
import com.suneasy.web.mod.util;


public class Upload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    SmartUpload mySmartUpload = new SmartUpload();

            try {

                mySmartUpload.initialize(this.getServletConfig(), request, response); // 设置长传操作的初始化
                mySmartUpload.setMaxFileSize(1024 * 1024 * 1024); // 设置上传文件的大小                                  
                mySmartUpload.upload();                                 
                Files files = mySmartUpload.getFiles(); // 获取上传的文件操作                                                                
                com.jspsmart.upload.File singleFile = files.getFile(0); // 获取上传文件的单个文件

                            if (!singleFile.isMissing()) { // 判断该文件是否被选择
                                String fileType = singleFile.getFileName().substring(singleFile.getFileName().length()-3);
                                String filename=System.currentTimeMillis() + "." + fileType;    
                                java.util.Date Datenow=new java.util.Date();//获取当前日期
                                java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMdd");  
                                String nowdate = formatter.format(Datenow); //将日期格式化
                                String realDirectory = request.getSession().getServletContext().getRealPath("/")+"video"+nowdate.substring(0,6);

                                filedir = realDirectory+"/" + filename; // 以系统时间作为上传文件名称,设置上传文件的完整路径
                                     File file = new File(realDirectory);

                                  if (!file.isDirectory()) { // 如果文件夹不存在就新建
                                        file.mkdirs();
                                        }

                                 singleFile.saveAs(filedir); // 执行上传操作  

                            }

            } catch (Exception e) {                                  
                e.printStackTrace();
            }   

            return;
    }

}
展开阅读全文

没有更多推荐了,返回首页