文件上传的基本原理,用文字详细说明一下

文件上传的基本原理,用文字详细说明一下,第1张

我借助别人的资料,感觉挺详细,仔细研究一下吧

文件上传与下载1。上传文件流程

先通过用户提交文件,保存文件到服务器端,然后在写入数据库中,每次到下载页好消面时从数据库中读出文件,生成文件在服务器目录中,以下。。。

文件上传后保存文件到服务器中jsp,

upFile.jsp

<%@ page contentType="text/htmlcharset=utf-8" language="java" %>

<import="java.util.List"%>

<html>

<head>

<title>上传文件</title>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8">

<base target="_self">

<link href="Css/style.css" rel="stylesheet">

<script type="text/javascript">

function check(){

var file = document.getElementById("file1").value

if(file == ""){

alert('请选择要上传的文件')

return false

}else{

window.returnValue=file

return true

}

}

</script>

</head>

<body>

<%

String files=request.getParameter("files")

%>

<form name="form2" enctype="multipart/form-data" method="post" action="../MissionManage/commonfile.jsp?files=<%=files %>" onsubmit="return check()">

<center>

<table align="center" width="350" height="150" border="0" cellpadding="0" cellspacing="0"><!-- background="images/upFile_bg.gif -->

<猜慎tr>

<td valign="top"><table width="100%" height="145" border="0" cellpadding="0" cellspacing="0">

<tr>

<友兆知td height="49" colspan="2"> </td>

</tr>

<tr>

<td width="9%" height="53"> </td>

<td width="91%"><b>请选择上传的文件:</b><br>

<input id="file1" name="file1" type="file" size="35" onkeydown="return false">

<br>

注:文件大小请控制在10M以内。</td>

</tr>

<tr>

<td colspan="2" align="center"><input name="Submit" type="submit" class="btn_grey" value="确认">

 

<input name="Submit2" type="button" class="btn_grey" onClick="window.close()" value="关闭"></td>

</tr>

</table></td>

</tr>

</table>

</center>

</form>

</body>

</html>

commonfile.jsp

<%@ page language="java" import="java.io.*" pageEncoding="UTF-8"%>

<import="java.util.*,org.apache.commons.fileupload.FileItem" %>

<import="java.text.SimpleDateFormat,java.util.Date" %>

<import="com.PoliceSystem.tools.FileOperate" %>

<jsp:useBean id="factory" scope="page" class="org.apache.commons.fileupload.disk.DiskFileItemFactory" />

<jsp:useBean id="upload" scope="page" class="org.apache.commons.fileupload.servlet.ServletFileUpload" />

<%

String path = request.getContextPath()

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>上传文件</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<base target="_self">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script type="text/javascript" language="javascript">

</script>

</head>

<body>

<%

request.setCharacterEncoding("UTF-8")

String path1 = (String)request.getRealPath("/upload1")

String files=request.getParameter("files")

String[] fileList=files.split("")

File file = new File(path1)

if(!file.exists()){

file.mkdirs()

}

factory.setRepository(file)

factory.setSizeThreshold(1024*1024)

upload.setFileItemFactory(factory)

try{

List<FileItem>list= upload.parseRequest(request)

for(FileItem item:list){

if(item.isFormField()){

//String value=item.getString("UTF-8")

//session.setAttribute("fileName", value)

}else{

String value=item.getName()

int start=value.lastIndexOf("\\")

String fileName=value.substring(start+1)

if(fileName.length() == 0 || fileName == ""){

out.println("<script>alert('上传失败')window.close()</script>")

}else{

if(item.getSize()>10000000){

out.println("<script>alert('对不起,您上传的文件超过10M,无法完成上传!')window.close()</script>")

}else{

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss")

Date date =new Date()

String[] f = item.getName().split("\\\\")

//System.out.println(f[f.length-1])

String oldFileName = f[f.length-1]

for(int i=0i<fileList.lengthi++){

if(fileList[i].indexOf(oldFileName)!=-1){

out.println("<script>alert('对不起,您上传的文件与现有上传的文件重名,请更换文件名重新上传!')window.returnValue=''window.close()</script>")

}

}

String fType = FileOperate.getFileType(item.getName())//文件类型

fileName = sdf.format(date)+"."+fType//新文件名

//System.out.println(item.getName()+"---"+fileName)

item.write(new java.io.File(path1,fileName))

//////--1--/////

String mailFileNames = new String()

String old = (String)session.getAttribute("fuJianFileNames")

if(old!=null){

mailFileNames = old

}

mailFileNames+=oldFileName+"|"+fileName+""

//System.out.println("mailFileNames="+mailFileNames)

session.removeAttribute("fuJianFileNames")

session.setAttribute("fuJianFileNames", mailFileNames)

//////--2--/////

//String pathName = path1+"

//System.out.println("pathName="+pathName)

out.println("<script>window.close()</script>")

}

}

}

}

}catch (Exception e) {

e.printStackTrace()

out.println("<script>window.close()</script>")

}

%>

</body>

</html>

插入文件数据到数据库中

public boolean insert_annex(String[] str){

boolean b=true

String sql =""

con = db.getConn()

try{

sql="insert into annex (querykey,sfilename,committime,Filetype,filepath,pno,Annex) values (?,?,?,?,?,?,?)"

ps = con.prepareStatement(sql)

for(int i=0i<str.length-1i++){

ps.setString(i+1, str[i])

}

File file = new File(str[6])//附件

InputStream iso = new FileInputStream(file)

ps.setBinaryStream(7, iso, iso.available())

ps.execute()

iso.close()

System.out.println("删除临时文件:" + file.delete())// 删除tmp文件

}catch(Exception e){

b=false

e.printStackTrace()

}finally{

this.close()

}

return b

}

读出文件数据,并保存

public boolean addTempFile_annex(String querykey,HttpServletRequest request){

boolean b=true

con = db.getConn()

InputStream in = null

OutputStream out= null

String path1 = (String)request.getRealPath("/upload1")//文件下载临时目录

try{

String sql="select filePath,annex from annex where querykey='"+querykey+"'"

//String sql_1="select annex from annex where querykey='"+querykey+"'"

ps = con.prepareStatement(sql)

rs=ps.executeQuery()

while(rs.next()){

File f = new File(path1+rs.getString("filepath"))

in=rs.getBinaryStream("annex")

out = new FileOutputStream(f)

int len = 10 * 100 * 100//定义字符数组长度

byte[] P_Buf=new byte[len]

int j

while((j=in.read(P_Buf))!=-1){

out.write(P_Buf, 0, j)

}

}

in.close()

out.flush()//强制清出缓冲区

out.close()

}catch(Exception e){

b=false

e.printStackTrace()

}finally{

this.close()

}

return b

}

给定传递过来的参数(文件名,文件存储在服务器的文件名,文件在服务器的路径,文件类型),下载文件Action

package com.PoliceSystem.action.mail

import java.io.File

import java.io.FileInputStream

import java.io.InputStream

import java.io.OutputStream

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import org.apache.struts2.ServletActionContext

import com.opensymphony.xwork2.ActionSupport

public class downLoadFile extends ActionSupport{

private static final long serialVersionUID = -2207648627734251737L

public String execute() throws Exception{

HttpServletRequest request = ServletActionContext.getRequest()

HttpServletResponse response = ServletActionContext.getResponse()

String fileminitype = request.getParameter("fileType")

String filename1 = new String(request.getParameter("fileName1").getBytes("ISO8859-1"),"UTF-8")

String filename2 = new String(request.getParameter("fileName2").getBytes("ISO8859-1"),"UTF-8")

String filepath = request.getRealPath("/upload1")

File f = new File(filepath+")

Long filelength = f.length()

int cacheTime = 10

response.setContentType(fileminitype)

response.setHeader("Location",filename1)

response.setHeader("Cache-Control", "max-age=" + cacheTime)

response.setContentType("application/octet-stream")

byte[] b = filename1.getBytes("GBK")

filename1 = new String(b,"8859_1")

response.setHeader("Content-Disposition", "attachmentfilename=" + filename1)

response.setContentLength(filelength.intValue())

OutputStream outputStream = response.getOutputStream()

InputStream inputStream = new FileInputStream(f)

byte[] buffer = new byte[1024]

int i = -1

while ((i = inputStream.read(buffer)) != -1) {

outputStream.write(buffer, 0, i)

}

outputStream.flush()

outputStream.close()

inputStream.close()

return null

}

}

MultipartFile提供了以下方锋饥法来获取上传文件的信息:

getOriginalFilename,获取上传的文件名字;

getBytes,获取上传文件内容,转为字节数组;

getInputStream,获取一个InputStream;

isEmpty,文件上传内容为空,或者根本就没有文件上传;

getSize,文件上传的大小。

transferTo(File dest),保存文件到目标文件系统;

同时上传多个文件,则使用MultipartFile数组类来接受多个文件上传:

//多文件上传@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)

    @ResponseBody    public String handleFileUpload(HttpServletRequest request){

        List<MultipartFile>files = ((MultipartHttpServletRequest) request)

                .getFiles("file")

        MultipartFile file = null

        BufferedOutputStream stream = null

        for (int i = 0i <files.size()++i) {

            file = files.get(i)

            if (!file.isEmpty()) {

                try {

           槐基陆         byte[] bytes = file.getBytes()

                    stream = new BufferedOutputStream(new FileOutputStream(

                            new File(file.getOriginalFilename())))

                    stream.write(bytes)

                    stream.close()

                } catch (Exception e) {

                    stream = null

                    return "You failed to upload " + i + " =>"                 铅顷           + e.getMessage()

                }

            } else {

                return "You failed to upload " + i

                        + " because the file was empty."

            }

        }

        return "upload successful"

    }

可以通过配置application.properties对SpringBoot上传的文件进行限定默认为如下配置:

spring.servlet.multipart.enabled=true

spring.servlet.multipart.file-size-threshold=0

spring.servlet.multipart.location=

spring.servlet.multipart.max-file-size=1MB

spring.servlet.multipart.max-request-size=10MB

spring.servlet.multipart.resolve-lazily=false

enabled默认为true,既允许附件上传。

file-size-threshold限定了当上传文件超过一定长度时,就先写到临时文件里。有助于上传文件不占用过多的内存,单位是MB或KB,默认0,既不限定阈值。

location指的是临时文件的存放目录,如果不设定,则web服务器提供一个临时目录。

max-file-size属性指定了单个文件的最大长度,默认1MB,max-request-size属性说明单次HTTP请求上传的最大长度,默认10MB.

resolve-lazily表示当文件和参数被访问的时候再被解析成文件。

文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全激陆郑路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据。

java中文件上传到服务器的指定路径的代码:悉孙

在前台界面中输入:

<form method="post" enctype="multipart/form-data"  action="../manage/excelImport.do">

请选文件:<input type="file"  name="excelFile">

<input type="submit" value="导入" onclick="return impExcel()"/>

</form>

action中获取前台传来数据并保存

/**

* excel 导入文件

* @return

* @throws IOException

*/

@RequestMapping("/usermanager/excelImport.do")

public String excelImport(

String filePath,

MultipartFile  excelFile,HttpServletRequest request) throws IOException{

log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" )

if (excelFile != null){

String filename=excelFile.getOriginalFilename()

String a=request.getRealPath("u/cms/www/201509")

SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename)//保存到服务器的路明颂径

}

log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" )

return ""

}

/**

* 将MultipartFile转化为file并保存到服务器上的某地

*/

public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException

{    

FileOutputStream fs=new FileOutputStream( path + "/"+ savefile)

System.out.println("------------"+path + "/"+ savefile)

byte[] buffer =new byte[1024*1024]

int bytesum = 0

int byteread = 0

while ((byteread=stream.read(buffer))!=-1)

{

bytesum+=byteread

fs.write(buffer,0,byteread)

fs.flush()

}

fs.close()

stream.close()

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12216750.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存