关于文件上传

Posted limorc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于文件上传相关的知识,希望对你有一定的参考价值。

1、依赖添加(注入pom.xml中)

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

2、配置文件上传解析器(配置在springMvc中)

<!--5、文件上传的解析器  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!--5.1 设置文件最大尺寸   5M-->
            <property name="maxUploadSize">
                <value>5242880</value>
            </property>
    </bean>

3、配置文件存储的位置(在web.Xml中)

 
<!-- 上传文件的存储位置 -->
      <context-param>
          <param-name>uploadPath</param-name>
          <param-value>G:\\apache-tomcat-8.5.31-windows-x64\\apache-tomcat-8.5.31\\webapps\\files</param-value>
      </context-param>

4、JSP

(1)     表单enctype为:enctype="multipart/form-data"

(2)     预览照片

 

技术图片

 

                   <div class="form-group">
                                    <label class="col-md-2 control-label" for="example-hf-password"
                                        style="margin: 0 0 0 135px;"> </label>
                                    <div class="col-md-4">
                                        <img id="img_1" src="<%=basePath%>images/11.jpg"
                                            style="box-shadow: 2px 3px 4px black; width: 200px; height: 250px;">
                                        <br> <br> <a href="javascript:;" class="file">选择文件
                                            <input type="file" name="posImgName" id="posImgName"
                                            onchange="previewImage(this,‘img_1‘)">
                                        </a>
                                    </div>
                                </div>

然后用一个input标签属性设置为file类型导入工具类UploadFileUtils、FileDownload

以下是UploadFileUtils

package cn.com.cxsw.ssm.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

public class UploadFileUtils 
    public static String uploadFile(HttpServletRequest request,MultipartFile adduserImg) throws Exception 
        String fileName="";
        String path = request.getServletContext().getInitParameter("uploadPath");
        String originalFilename = adduserImg.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        fileName=UUID.randomUUID().toString().replaceAll("-", "")+substring;
        File targetFile=new File(path+"\\\\"+fileName);
        try 
            adduserImg.transferTo(targetFile);
         catch (Exception e) 
            e.printStackTrace();
        
        return fileName;
    
    public static List<String> multiFileUpload(MultipartFile[] multipartFiles,HttpServletRequest request) throws
    IllegalStateException, IOException
    List<String> fileNameList=new ArrayList<String>();
    // 0、获取服务器中文件存储的位置
    String pathDir=request.getServletContext().getInitParameter("imgPath");
    for(MultipartFile multipartFile:multipartFiles) 
    // 1、获取原始照片的名称
    String oldFileName = multipartFile.getOriginalFilename();
    // 2、解析出源文件的扩展名
    String extendsName = oldFileName.substring(oldFileName.indexOf("."));
    // 3、生成新的文件名称
    String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + extendsName;
    // 4、创建目标文件对象
    File file = new File(pathDir + newFileName);
    // 5、写入目标文件
    multipartFile.transferTo(file);
    // 6、存入新文件名
    fileNameList.add(newFileName);
    
    return fileNameList;
    
    

FileDownload

package cn.com.cxsw.ssm.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class FileDownload 
    public static void downloadFile(HttpServletResponse response, String filePath) 
        // 映射下载文件
        File file = new File(filePath);
        if (file.exists()) 
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try 
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) 
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                
             catch (Exception e) 
                e.printStackTrace();
             finally 
                if (bis != null) 
                    try 
                        bis.close();
                     catch (IOException e) 
                        e.printStackTrace();
                    
                
                if (fis != null) 
                    try 
                        fis.close();
                     catch (IOException e) 
                        e.printStackTrace();
                    
                
                if (os != null) 
                    try 
                        os.close();
                     catch (IOException e) 
                        e.printStackTrace();
                    
                
            
        
    

web.xml中要设置存储路径:

<context-param>
        <param-name>uploadPath</param-name>
        <param-value>G:\\apache-tomcat-8.5.31-windows-x64\\apache-tomcat-8.5.31\\webapps\\myFiles</param-value>
    </context-param>

5、controller中,首先用MultipartFile获取数据为jsp中file的name属性,还有http的请求HttpServletRequest request其次在封装的UploadFileUtils类中使用uploadFile方法传入值即可完成

@RequestMapping(value = "/posterAdd", method =  RequestMethod.POST, RequestMethod.GET )
    public String posterAdd(PosterInfo posterInfo, MultipartFile posImgName, HttpServletRequest request) 
        String newFileName = "";
        try 
            newFileName = UploadFileUtils.uploadFile(request, posImgName);
         catch (Exception e) 
            e.printStackTrace();
        
        posterInfo.setPosImg(newFileName);
        String posIdcard = posterInfo.getPosIdcard();
        String psw = posIdcard.substring(11,17);
        posterInfo.setPosPsw(psw);
        int res1 = posterInfoServiceImpl.insert(posterInfo);
        return "poster/poster_add";
    

 

以上是关于关于文件上传的主要内容,如果未能解决你的问题,请参考以下文章

关于文件上传功能的思考

关于MVC4里面的大文件上传,该怎么解决

关于上传文件的内容

关于svn里面不能上传文件的问题

关于文件上传漏洞

Java Web项目实现上传文件以及下载文件功能的关于路径的问题