jspservlet實現上傳
A. jsp 大文件分片上傳處理如何實現
javaweb上傳文件
上傳文件的jsp中的部分
上傳文件同樣可以使用form表單向後端發請求,也可以使用 ajax向後端發請求
    1.通過form表單向後端發送請求
         <form id="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
            <div class="bbxx wrap">
                <inputtype="text" id="side-profile-name" name="username" class="form-control">
                <inputtype="file" id="example-file-input" name="avatar">
                <button type="submit" class="btn btn-effect-ripple btn-primary">Save</button>
            </div>
        </form>
改進後的代碼不需要form標簽,直接由控制項來實現。開發人員只需要關注業務邏輯即可。JS中已經幫我們封閉好了
    this.post_file = function ()
    {
        $.each(this.ui.btn, function (i, n) { n.hide();});
        this.ui.btn.stop.show();
        this.State = this.Config.state.Posting;//
        this.app.postFile({ id: this.fileSvr.id, pathLoc: this.fileSvr.pathLoc, pathSvr:this.fileSvr.pathSvr,lenSvr: this.fileSvr.lenSvr, fields: this.fields });
    };
通過監控工具可以看到控制項提交的數據,非常的清晰,調試也非常的簡單。
2.通過ajax向後端發送請求
            $.ajax({
                 url : "${pageContext.request.contextPath}/UploadServlet",
                 type : "POST",
                 data : $( '#postForm').serialize(),
                 success : function(data) {
                      $( '#serverResponse').html(data);
                 },
                 error : function(data) {
                      $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);
                 }
            });
ajax分為兩部分,一部分是初始化,文件在上傳前通過AJAX請求通知服務端進行初始化操作
    this.md5_complete = function (json)
    {
        this.fileSvr.md5 = json.md5;
        this.ui.msg.text("MD5計算完畢,開始連接伺服器...");
        this.event.md5Complete(this, json.md5);//biz event
 
        var loc_path = encodeURIComponent(this.fileSvr.pathLoc);
        var loc_len = this.fileSvr.lenLoc;
        var loc_size = this.fileSvr.sizeLoc;
        var param = jQuery.extend({}, this.fields, this.Config.bizData, { md5: json.md5, id: this.fileSvr.id, lenLoc: loc_len, sizeLoc: loc_size, pathLoc: loc_path, time: new Date().getTime() });
 
        $.ajax({
            type: "GET"
            , dataType: 'jsonp'
            , jsonp: "callback" //自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名
            , url: this.Config["UrlCreate"]
            , data: param
            , success: function (sv)
            {
                _this.svr_create(sv);
            }
            , error: function (req, txt, err)
            {
                _this.Manager.RemoveQueuePost(_this.fileSvr.id);
                alert("向伺服器發送MD5信息錯誤!" + req.responseText);
                _this.ui.msg.text("向伺服器發送MD5信息錯誤");
                _this.ui.btn.cancel.show();
                _this.ui.btn.stop.hide();
            }
            , complete: function (req, sta) { req = null; }
        });
    };
 
在文件上傳完後向伺服器發送通知
    this.post_complete = function (json)
    {
        this.fileSvr.perSvr = "100%";
        this.fileSvr.complete = true;
        $.each(this.ui.btn, function (i, n)
        {
            n.hide();
        });
        this.ui.process.css("width", "100%");
        this.ui.percent.text("(100%)");
        this.ui.msg.text("上傳完成");
        this.Manager.arrFilesComplete.push(this);
        this.State = this.Config.state.Complete;
        //從上傳列表中刪除
        this.Manager.RemoveQueuePost(this.fileSvr.id);
        //從未上傳列表中刪除
        this.Manager.RemoveQueueWait(this.fileSvr.id);
 
        var param = { md5: this.fileSvr.md5, uid: this.uid, id: this.fileSvr.id, time: new Date().getTime() };
 
        $.ajax({
            type: "GET"
              , dataType: 'jsonp'
              , jsonp: "callback" //自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名
              , url: _this.Config["UrlComplete"]
              , data: param
              , success: function (msg)
              {
                  _this.event.fileComplete(_this);//觸發事件
                  _this.post_next();
              }
              , error: function (req, txt, err) { alert("文件-向伺服器發送Complete信息錯誤!" + req.responseText); }
              , complete: function (req, sta) { req = null; }
        });
    };
 
這里需要處理一個MD5秒傳的邏輯,當伺服器存在相同文件時,不需要用戶再上傳,而是直接通知用戶秒傳
    this.post_complete_quick = function ()
    {
        this.fileSvr.perSvr = "100%";
        this.fileSvr.complete = true;
        this.ui.btn.stop.hide();
        this.ui.process.css("width", "100%");
        this.ui.percent.text("(100%)");
        this.ui.msg.text("伺服器存在相同文件,快速上傳成功。");
        this.Manager.arrFilesComplete.push(this);
        this.State = this.Config.state.Complete;
        //從上傳列表中刪除
        this.Manager.RemoveQueuePost(this.fileSvr.id);
        //從未上傳列表中刪除
        this.Manager.RemoveQueueWait(this.fileSvr.id);
        //添加到文件列表
        this.post_next();
        this.event.fileComplete(this);//觸發事件
    };
這里可以看到秒傳的邏輯是非常 簡單的,並不是特別的復雜。
            var form = new FormData();
            form.append("username","zxj");
            form.append("avatar",file);
            //var form = new FormData($("#postForm")[0]);
            $.ajax({
                url:"${pageContext.request.contextPath}/UploadServlet",
                type:"post",
                data:form,
                processData:false,
                contentType:false,
                success:function(data){
        
                    console.log(data);
                }
            });
java部分
文件初始化的邏輯,主要代碼如下
FileInf fileSvr= new FileInf();
fileSvr.id = id;
fileSvr.fdChild = false;
fileSvr.uid = Integer.parseInt(uid);
fileSvr.nameLoc = PathTool.getName(pathLoc);
fileSvr.pathLoc = pathLoc;
fileSvr.lenLoc = Long.parseLong(lenLoc);
fileSvr.sizeLoc = sizeLoc;
fileSvr.deleted = false;
fileSvr.md5 = md5;
fileSvr.nameSvr = fileSvr.nameLoc;
 
//所有單個文件均以uuid/file方式存儲
PathBuilderUuid pb = new PathBuilderUuid();
fileSvr.pathSvr = pb.genFile(fileSvr.uid,fileSvr);
fileSvr.pathSvr = fileSvr.pathSvr.replace("\\","/");
 
DBConfig cfg = new DBConfig();
DBFile db = cfg.db();
FileInf fileExist = new FileInf();
    
boolean exist = db.exist_file(md5,fileExist);
//資料庫已存在相同文件,且有上傳進度,則直接使用此信息
if(exist && fileExist.lenSvr > 1)
{
     fileSvr.nameSvr             = fileExist.nameSvr;
     fileSvr.pathSvr        = fileExist.pathSvr;
     fileSvr.perSvr              = fileExist.perSvr;
     fileSvr.lenSvr              = fileExist.lenSvr;
     fileSvr.complete       = fileExist.complete;
     db.Add(fileSvr);
    
     //觸發事件
    up6_biz_event.file_create_same(fileSvr);
}//此文件不存在
else
{
     db.Add(fileSvr);
     //觸發事件
    up6_biz_event.file_create(fileSvr);
    
     FileBlockWriter fr = new FileBlockWriter();
     fr.CreateFile(fileSvr.pathSvr,fileSvr.lenLoc);
}
接收文件塊數據,在這個邏輯中我們接收文件塊數據。控制項對數據進行了優化,可以方便調試。如果用監控工具可以看到控制項提交的數據。
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();  
ServletFileUpload upload = new ServletFileUpload(factory);
List files = null;
try
{
     files = upload.parseRequest(request);
}
catch (FileUploadException e)
{// 解析文件數據錯誤 
    out.println("read file data error:" + e.toString());
    return;
  
}
 
FileItem rangeFile = null;
// 得到所有上傳的文件
Iterator fileItr = files.iterator();
// 循環處理所有文件
while (fileItr.hasNext())
{
     // 得到當前文件
     rangeFile = (FileItem) fileItr.next();
     if(StringUtils.equals( rangeFile.getFieldName(),"pathSvr"))
     {
         pathSvr = rangeFile.getString();
         pathSvr = PathTool.url_decode(pathSvr);
     }
}
 
boolean verify = false;
String msg = "";
String md5Svr = "";
long blockSizeSvr = rangeFile.getSize();
if(!StringUtils.isBlank(blockMd5))
{
     md5Svr = Md5Tool.fileToMD5(rangeFile.getInputStream());
}
 
verify = Integer.parseInt(blockSize) == blockSizeSvr;
if(!verify)
{
     msg = "block size error sizeSvr:" + blockSizeSvr + "sizeLoc:" + blockSize;
}
 
if(verify && !StringUtils.isBlank(blockMd5))
{
     verify = md5Svr.equals(blockMd5);
     if(!verify) msg = "block md5 error";
}
 
if(verify)
{
     //保存文件塊數據
     FileBlockWriter res = new FileBlockWriter();
     //僅第一塊創建
     if( Integer.parseInt(blockIndex)==1) res.CreateFile(pathSvr,Long.parseLong(lenLoc));
     res.write( Long.parseLong(blockOffset),pathSvr,rangeFile);
     up6_biz_event.file_post_block(id,Integer.parseInt(blockIndex));
    
     JSONObject o = new JSONObject();
     o.put("msg", "ok");
     o.put("md5", md5Svr); 
     o.put("offset", blockOffset);//基於文件的塊偏移位置
     msg = o.toString();
}
rangeFile.delete();
out.write(msg);
B. 用jsp、java實現上傳圖片,保存到資料庫,從資料庫中提取,顯示到頁面 這四步 我想問第一步,怎麼上傳圖片
用jspSmartUpload組件來實現,用jsp+servlet在Servlet里實現的代碼:
PrintWriter out = response.getWriter();
  int count = 0;
  // 實例化上傳控制項對象
  SmartUpload su = new SmartUpload();
  // 初始化操作
  su.initialize(config, request, response);
  
  // 設置上傳文件最大位元組數
  su.setTotalMaxFileSize(100000);
  
  // 
  try {
                          //禁止上傳指定擴展名的文件
   su.setDeniedFilesList("ext,bat,jsp");
  } catch (SQLException e1) {
   e1.printStackTrace();
  }
  
  try {
   // 上傳文件到伺服器
   su.upload();
   
   File fileup = new File(request.getRealPath("upload"));
   if(!fileup.exists()){
    // 創建目錄
    fileup.mkdir();
   }
   // 處理多個文件的上傳
   for(int i = 0;i < su.getFiles().getCount();i++){
    com.jspsmart.upload.File file = su.getFiles().getFile(i);
    if(!file.isMissing()){ // 如果文件有效
     // 保存文件到指定上傳目錄
     file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
     count = su.save("/upload");
    }
   }
} catch (SmartUploadException e) {
   e.printStackTrace();
  }
  out.println(count +"file(s) uploaded");
如果你對這個上傳組件不了解,最好是先去查查用法。。。 
如果對您有幫助,請記得採納為滿意答案,謝謝!祝您生活愉快!
 vaela
C. jsp+servlet 怎麼實現文件上傳
你要做文件上傳吧 form表單里一定要設置這兩個值enctype="multipart/form-data" method="post"
上傳成功後會在tomcat里有那個文件 ,至於你說的要獲取io流。那就需要找到那個文件給你寫一下偽碼吧:
 //獲得上傳文件的路徑
 String path = getServletContext().getRealPath(webpath);
 
 File file = new File(path);
 file.getParentFile().mkdirs();
 file.createNewFile();
// 獲得流
 InputStream in = item.getInputStream();
 OutputStream out = new FileOutputStream(file);
不懂的再問我!
建議你用個上傳組件,fileupload什麼的
D. jsp+servlet實現文件上傳與下載源碼
上傳:
需要導入兩個包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * 上傳附件
 * @author new
 *
 */
public class UploadAnnexServlet extends HttpServlet {
 private static String path = "";
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 /*
  * post處理
  * (non-Javadoc)
  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  path = this.getServletContext().getRealPath("/upload");
  try {
   DiskFileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload up = new ServletFileUpload(factory);
   List<FileItem> ls = up.parseRequest(request);
   for (FileItem fileItem : ls) {
    if (fileItem.isFormField()) {
     String FieldName = fileItem.getFieldName();
     //getName()返回的是文件名字 普通域沒有文件 返回NULL
     //                    String Name = fileItem.getName();
     String Content = fileItem.getString("gbk");
     request.setAttribute(FieldName, Content);
    } else {
    
     String nm = fileItem.getName().substring(
       fileItem.getName().lastIndexOf("\\") + 1);
     File mkr = new File(path, nm);
     if (mkr.createNewFile()) {
      fileItem.write(mkr);//非常方便的方法
     }
     request.setAttribute("result", "上傳文件成功!");
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("result", "上傳失敗,請查找原因,重新再試!");
  }
  request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
    request, response);
 }
} 
下載(i/o流)無需導包:
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 下載文件
 * @author
 *
 */
public class DownloadFilesServlet extends HttpServlet {
 /**
  * 
  */
 private static final long serialVersionUID = 8594448765428224944L;
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 /*
  * 處理請求
  * (non-Javadoc)
  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String name = request.getParameter("fileName");
  System.out.print("dddddddddd:" + name);
  // web絕對路徑
  String path = request.getSession().getServletContext().getRealPath("/");
  String savePath = path + "upload";
  // 設置為下載application/x-download
  response.setContentType("application/x-download");
  // 即將下載的文件在伺服器上的絕對路徑
  String filenamedownload = savePath + "/" + name;
  // 下載文件時顯示的文件保存名稱
  String filenamedisplay = name;
  // 中文編碼轉換
  filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
  response.addHeader("Content-Disposition", "attachment;filename="
    + filenamedisplay);
  try {
   java.io.OutputStream os = response.getOutputStream();
   java.io.FileInputStream fis = new java.io.FileInputStream(
     filenamedownload);
   byte[] b = new byte[1024];
   int i = 0;
   while ((i = fis.read(b)) > 0) {
    os.write(b, 0, i);
   }
   fis.close();
   os.flush();
   os.close();
  } catch (Exception e) {
  }
 }
}
