ajax+springMvc+maven实现文件上传

javaWeb文件上传

技术相关:前端jquery 后台springMvc

多种不同的文件上传

前端file.js代码
 
//判断文件大小
function judge(file){
    fileSize=file.size;
    var size = fileSize / 1024;
    if (size > 1024 * 500)
    {
        alert("文件上传限制500M");
        return;
    }
}
//普通文件上传
$('#upload0').on('click',function () {
    var formData = new FormData();

    formData.append('name',"普通文件上传");

    if ($('#file0')[0].files[0] != null)
    {
        formData.append("file",$('#file0')[0].files[0]);
    }


    $.ajax({
        type: "post",//请求方式
        url: '../siample/upload',
        timeout: 600000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
        dataType: "json", //返回格式
        data:formData,
        processData : false, // 使数据不做处理
        contentType : false, // 不要设置Content-Type请求头
        success: function (data, textStatus) {
            //console.log(data);
            alert("文件上传成功");

        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
});

//文件上传1
$('#upload1').on('click',function () {
    var formData = new FormData();
    formData.append('name',"限制文件上传");

    if ($('#file1')[0].files[0] != null)
    {
        formData.append("file",$('#file1')[0].files[0]);
    }


    $.ajax({
        type: "post",//请求方式
        url: '../siample/upload',
        timeout: 600000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
        dataType: "json", //返回格式
        data:formData,
        processData : false, // 使数据不做处理
        contentType : false, // 不要设置Content-Type请求头
        success: function (data, textStatus) {
            //console.log(data);
            alert("文件上传成功");
        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
});
//文件上传2
$('#upload2').on('click',function () {
    var formData = new FormData();
    formData.append('name',"多文件上传");

    for (var i = 0; i < $('#file2')[0].files.length; i++) {
        var argument = $('#file2')[0].files[i];
        formData.append("file",argument);

    }

        alert("文件上传成功");



    $.ajax({
        type: "post",//请求方式
        url: '../siample/uploads',
        timeout: 600000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
        dataType: "json", //返回格式
        data:formData,
        processData : false, // 使数据不做处理
        contentType : false, // 不要设置Content-Type请求头
        success: function (data, textStatus) {
            //console.log(data);
            alert("文件上传成功");

        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
});


//文件上传3
$('#upload3').on('click',function () {
    var formData = new FormData();
    formData.append('name',"随意文件上传");

    if ($('#file0')[0].files[0] != null)
    {
        formData.append("file",$('#file3')[0].files[0]);
    }


    $.ajax({
        type: "post",//请求方式
        url: '../siample/uploadr',
        timeout: 600000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
        dataType: "json", //返回格式
        data:formData,
        processData : false, // 使数据不做处理
        contentType : false, // 不要设置Content-Type请求头
        success: function (data, textStatus) {
            //console.log(data);
            alert("文件上传成功");

        },
        error: function (jqXHR, textStatus, errorThrown) {
        }
    });
});

file.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>

<div style = "margin: 100px">
    <p>文件上传</p>
    普通文件上传:<input id = "file0" type="file" />
    <button id = "upload0">上传</button>

</div>

<div  style = "margin: 100px">
    <p>文件上传</p>
    限制文件上传:<input id = "file1" type="file" accept="image/*"/>
    <button id = "upload1">上传</button>
</div>

<div  style = "margin: 100px">
    <p>多文件上传</p>
    多文件上传:<input id = "file2" type="file" multiple />
    <button id = "upload2">上传</button>
</div>

<div  style = "margin: 100px">
    <p>上传文件无论上不上传都可以</p>
    随意文件上传:<input id = "file3" type="file" />
    <button id = "upload3">上传</button>
</div>

<div></div>
</body>
<script src = "../js/jquery-2.0.3.min.js" type = "text/javascript"></script>
<script src = "../js/file.js" type="text/javascript"></script>
</html>
后台代码实现

controller

package com.file.controller;

import com.file.comm.bean.FileResponse;
import com.file.service.FileUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

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

/**
 * 普通文件上传的几种情况
 */
@Controller
@RequestMapping("/siample")
public class FileUploadController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private FileUploadService fileUploadService;


    /**
     * 普通文件上传+前端文件类型限制
     * @param name
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public FileResponse fileUpload(@RequestParam("name")String name, @RequestParam("file")MultipartFile file){
        
        fileUploadService.saveFile(file);
        logger.info("普通文件上传");
        return new FileResponse();
    }

    /**
     * 多文件上传
     * @param name
     * @param files
     * @return
     */
@RequestMapping("/uploads")
    @ResponseBody
    public FileResponse fileUploads(@RequestParam("name")String name, @RequestParam("file")MultipartFile[] files){

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            fileUploadService.saveFile(file);
        }
        logger.info("多文件上传");

        return new FileResponse();
    }

    /**
     * 随意文件上传
     * @return
     */
    @RequestMapping("/uploadr")
    @ResponseBody
    public FileResponse fileUploadr(HttpServletRequest request, HttpServletResponse response){
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = mRequest.getFile("file");
        if(file != null){
            fileUploadService.saveFile(file);
        }
        logger.info("随意文件上传");




        return new FileResponse();
    }

}

后台service层的代码

package com.file.service.impl;


import com.file.controller.TestController;
import com.file.service.FileUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 普通文件上传的逻辑端
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);
    @Override
    public void saveFile(MultipartFile file) {

        //更据当前时间设置文件名
        //SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        //String filename = df.format(new Date())+file.getOriginalFilename();

        String fileName = file.getOriginalFilename();

        //获取到文件的classes路径,让前端直接可以通过url访问
        //String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        //path = path.substring(0, path.indexOf("/WEB-INF"));

        String path = "F:/test";
       //创建文件夹
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 在文件夹下新建一个filename文件的文件对象,此处新建文件应该新建在确切的物理路径下
        File targetFile = new File(path+"/" + fileName);

        // 判断真实路径下是否存在filename文件
        if (!targetFile.exists()) {
            try {
                // 在真实路径下创建filename空文件
                targetFile.createNewFile();
            } catch (IOException e) {
                logger.error("创建文件:{}出错",fileName,e);
            }
        }
        try {
            // 复制文件到真实路径下
            file.transferTo(targetFile);
        } catch (Exception e) {
            logger.error("创建文件失败",e);
        }
    }
}

以上是对文件上传几种简单情况的实现,最普通的一种文件上传,前端限制文件上传格式的上传文件,多文件上传。还有一个是项目遇到的一个情况,当你让用户上传文件时,用户可以不选择上传文件,但是要跟着上传其他字段,直接将文件对象上传null,用普通文件的上传后台接收代码是不行的 ,通过request获取就可以解决这个问题。

上述代码中还有一个文件上传的简单大小判断,可以用来限制文件上传的大小。

function judge(file){
    fileSize=file.size;
    var size = fileSize / 1024;
    if (size > 1024 * 500)
    {
        alert("文件上传限制500M");
        return;
    }
}

文件下载

文件下载的实现十分的简单,利用原生的a标签的herf拼接参数,点击跳转就可。

后台文件下载的代码实现

	public void loadFile(String fileName,HttpServletRequest request,HttpServletResponse response) {
		//下面这2行是对文件夹的目录的拼接
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		path = path.substring(0, path.indexOf("/WEB-INF"));
		response.setContentType("text/html;charset=utf-8");

		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			logger.error("设置请求编码出错",e);
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String downLoadPath = path+"/"+fileName;
		try {
			long fileLength = new File(downLoadPath).length();


			response.setContentType("application/x-msdownload");
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(fileName.substring(fileName.lastIndexOf("/")).getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead; 
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
																		
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			logger.error("读取文件出错",e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error("关闭流出错", e);
				}
			}
			if (bos != null) {
				try {
					bos.close();// 10.关闭缓存输出流对象
				} catch (IOException e) {
					logger.error("关闭流出错", e);
				}
			}
		}

	}

我使用了idea搭建了一个简单的文件上传项目,上述的代码都在其中,github的地址为https://github.com/swj19980812/fileload
我的博客地址https://www.swjnzb.cn/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值