Java实现文件上传的两种方法(uploadify和Spring)

网友投稿 316 2023-03-15


Java实现文件上传的两种方法(uploadify和Spring)

最近项目中用到的两种文件上传方式做一下总结:

一. uploadify:

uploadify控件的scripts和styles在这里:图片上传

jsP:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ include file="../jsp/include/taglibs.jsp"%>

" type="text/javascript">

">

">

">

">

">

">

" rel="stylesheet" type="text/css" />

" type="text/javascript">

">

后台Java:

package com.sun.fileUpload;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Date;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

@Controller

public class upload{

// 附件上传

@RequestMapping("/uploadAttach.do")

public void attachUpload(ModelMap modelMap,HttpServletRequest request ,HttpServletResponse response) throws IOException {

System.out.println("upload file .... start");

String savePath = request.getSession().getServletContext().getRealPath("/") + "upload";

System.out.println("store path is :" + savePath);

File f1 = new File(savePath);

if (!f1.exists()) {

f1.mkdirs();

}

DiskFileItemFactory fac = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(fac);

upload.setHeaderEncoding("utf-8");

List fileList = null;

try {

fileList = upload.parseRequest(request);

} catch (FileUploadException ex) {

ex.printStackTrace();

return;

}

Iterator it = fileList.iterator();

String name = "";

System.out.println("deal the files ... start");

//存储完毕保存进入数据库

//Document document = null;

while (it.hasNext()) {

FileItem item = it.next();

if (!item.isFormField()) {

name = item.getName();

long size = item.getSize();

String type = item.getContentType();

if (name == null || name.trim().equals("")) {

continue;

}

System.out.println("dealing file info:" + "fileName" + name + " size" + size + " type:" + type);

//扩展名格式:

if (name.lastIndexOf(".") >= 0) {

name.suyyHlzbstring(name.lastIndexOf("."));

}

//存文件到磁盘指定路径 且存储文件记录存入数据库,如果存储发生故障,数据库记录也会创建失败

/* document = new Document();

document.setFileType(extName);

document.setFullName(name);

document.setDescription(name);

document.setName(name);

document.setUploadDate(new Date());

document = documentManager.saveWithFileStore(document,item,savePath,extName);*/

System.out.println(new Date() + "persist id :" + name);

File saveFile = new File(savePath + "/" + name);

try {

item.write(saveFile);

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(new Date() + "store file error");

}

}

}

System.out.println("deal the files end");

System.out.println("upload file .... end");

response.getWriter().print(name + "@" + name);

}

}

这里把数据库更新给省略了,有需要可以自己添加。

除上传外,其他实现功能:

1. 视频上传后的预览功能

2. 视频是单文http://件上传,附件是多文件上传和删除

二. Spring默认的上传功能:

JSP:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ include file="../jsp/include/taglibs.jsp"%>

" type="text/javascript">

">

点击保存后上传:

选择文件

后台Java:

package com.sun.fileUpload;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Date;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

@Controller

public class upload{

@RequestMapping(value = "/uploadFile.do")

public String uploadController(HttpServletRequest request,ModelMap modelMap,

@RequestParam("videoFile") MultipartFile videoFile) throws IllegalStateException, IOException{

String savePath = request.getSession().getServletContext().getRealPath("/") + "upload";

try {

uploadSingleFile(savePath, videoFile, request.getSession().getServletContext().getRealPath("/"));

}catch (Exception e) {

return "/upload";

}

modelMap.addAttribute("uploadfile", "upload/" + videoFile.getOriginalFilename());

return "/upload";

}

/**

*

* @param path 这个path 是upload的子目录路径 比如 path=/image 最终将下载到[root/upload/image/]目录下

* @param file

* @return

* @throws java.io.IOException

*/

public static String uploadSingleFile(String path, MultipartFile file, String rootPath) {

if (!file.isEmpty()) {

byte[] bytes;

try {

bytes = file.getBytes();

// Create the file on server

File serverFile = new File(path + "/" + file.getOriginalFilename());

BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));

stream.write(bytes);

stream.close();

System.out.println("Server File Location=" + serverFile.getAbsolutePath());

return getRelativePathFromUploadDir(serverFile, rootPath).replaceAll("\\\\", "/");

} catch (IOException e) {

e.printStackTrace();

}

}else{

System.out.println("文件内容为空");

}

return null;

}

/**

*

* @param file

* @return 返回从upload目录下面的相对路径

*/

public static String getRelativePathFromUploadDir(File file, String rootPath){

if(null==file)

return "";

String absolutePath = file.getAbsolutePath();

if(absolutePath.indexOf(rootPath)!=-1 && rootPath.length()

return absolutePath.substring(absolutePath.indexOf(rootPath)+rootPath.length());

else

return "";

}

}

Spring配置文件springmvc-servlet.xml中添加:

如果和uploadify同时使用的话,需要做一些修改,否则uploadify的上传文件会被Spring拦截:

lt;bean id="multipartResolver" class="org.sun.com.MyMultipartResolver">

UTF-8

lt;/bean>

org.sun.com.MyMultipartResolver:

package org.sun.com;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**

* @author Sun

*/

public class MyMultipartResolver extends CommonsMultipartResolver {

private String excludeUrls;

private String[] excludeUrlArray;

public String getExcludeUrls() {

return excludeUrls;

}

public void setExcludeUrls(String excludeUrls) {

this.excludeUrls = excludeUrls;

this.excludeUrlArray = excludeUrls.split(",");

}

/**

* 这里是处理Multipart http的方法。如果这个返回值为true,那么Multipart http body就会MyMultipartResolver 消耗掉.如果这里返回false

* 那么就会交给后面的自己写的处理函数处理例如刚才ServletFileUpload 所在的函数

* @see org.springframework.web.multipart.commons.CommonsMultipartResolver#isMultipart(javax.servlet.http.HttpServletRequest)

*/

@Override

public boolean isMultipart(HttpServletRequest request) {

for (String url: excludeUrlArray) {

// 这里可以自己换判断

if (request.getRequestURI().contains(url)) {

return false;

}

}

return super.isMultipart(request);

}

}

return absolutePath.substring(absolutePath.indexOf(rootPath)+rootPath.length());

else

return "";

}

}

Spring配置文件springmvc-servlet.xml中添加:

如果和uploadify同时使用的话,需要做一些修改,否则uploadify的上传文件会被Spring拦截:

lt;bean id="multipartResolver" class="org.sun.com.MyMultipartResolver">

UTF-8

lt;/bean>

org.sun.com.MyMultipartResolver:

package org.sun.com;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**

* @author Sun

*/

public class MyMultipartResolver extends CommonsMultipartResolver {

private String excludeUrls;

private String[] excludeUrlArray;

public String getExcludeUrls() {

return excludeUrls;

}

public void setExcludeUrls(String excludeUrls) {

this.excludeUrls = excludeUrls;

this.excludeUrlArray = excludeUrls.split(",");

}

/**

* 这里是处理Multipart http的方法。如果这个返回值为true,那么Multipart http body就会MyMultipartResolver 消耗掉.如果这里返回false

* 那么就会交给后面的自己写的处理函数处理例如刚才ServletFileUpload 所在的函数

* @see org.springframework.web.multipart.commons.CommonsMultipartResolver#isMultipart(javax.servlet.http.HttpServletRequest)

*/

@Override

public boolean isMultipart(HttpServletRequest request) {

for (String url: excludeUrlArray) {

// 这里可以自己换判断

if (request.getRequestURI().contains(url)) {

return false;

}

}

return super.isMultipart(request);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:网关api怎么设置(网关的设置规则1和254)
下一篇:Vue + Vue
相关文章

 发表评论

暂时没有评论,来抢沙发吧~