SSM项目中上传文件和图片

最近做文件上传费了些功夫,记录下使用方法。

1.依赖配置

        
        
            commons-io
            commons-io
            2.6
        
        
            commons-fileupload
            commons-fileupload
            1.3.3
        
        

2.在springmvc.xml文件中配置文件解析器,配置文件上传的限制。

    
    
        
        
            5242880
        
        
            UTF-8
        
    

3.配置虚拟路径

实际项目中,不可能将上传的文件和图片保存在项目路径中,这样会导致项目崩溃。比较合理的做法是将上传的文件和图片存在本地的磁盘中,Tomcat中绑定一个虚拟路径。Tomcat下conf目录中的server.xml文件,在 中添加,这句话的意思是说存储在H:/data/file文件夹下的文件可以通过http://localhost:8080/file来访问。


        
        
      

4.编写Controller

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
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 java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
 * Created by Tomthy on 2018/5/17
 */
/**
 * 文件、图片上传
 */
@Controller
public class UploadFileController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);
    //文件上传相关代码
    @RequestMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile fileUpload) throws IOException {
        // 下面是图片上传的代码
            // 得到图片的原始文件名
            String originalName = fileUpload.getOriginalFilename();
            // 指定带盘符的路径, 物理路径
            String realPath = "H://data//file//";
            /**
             * 为了处理出现重名现象, 将原始文件名去掉,
             * 通过UUID算法生成新的文件名
             */
            String uuidName = UUID.randomUUID().toString();
            // uuid名称加上文件的后缀名
            String newFile = uuidName + originalName.substring(originalName.lastIndexOf("."));
            // 创建File文件
            File file = new File(realPath + newFile);
            // 将图片写入到具体的位置
            fileUpload.transferTo(file);
            // 将文件名保存到数据库
//            items.setPic(newFile);
            return "http://localhost:8080/file/"+newFile;
    }
}

5.编写前台页面


以后补充


你可能感兴趣的:(SSM项目中上传文件和图片)