图片/文件上传 ( fastDFS , SpringMVC )

1. 图片上传

  • 使用 fastDFS 服务器

(1) 引入依赖

< dependency>
    < groupId>org.csource.fastdfsgroupId>
    < artifactId>fastdfsartifactId>
    < version>1.2version>
dependency>
< dependency>
    < groupId>commons-fileuploadgroupId>
    < artifactId>commons-fileuploadartifactId>
    < version>1.3.1version>
dependency>

(2) 添加配置 application.properties

  • 用于属性注入: @Value( "${FILE_SERVER_URL}"), 后续将返回的上传图片的 url 和服务器 ip 地址,拼装成完整的 url
FILE_SERVER_URL= http://192.168.12.169/

(3) 添加配置 client.conf

  • 用于创建 FastDFS 的客户端
#图片服务器连接地址
tracker_server=192.168.12.169:22122

(4) 在 springmvc.xml 添加配置

  • 将 CommonsMultipartResolver 创建对象,加入 IOC 容器

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property  name="defaultEncoding"  value="utf-8" >property>
    
    <property  name="maxUploadSize"  value" ="10240000" >property>
bean>
  • 以上配置如下图:

图片/文件上传 ( fastDFS , SpringMVC )_第1张图片

(5) controller 层代码

import com.pojo.ResultInfo;
import com.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping( "upload")
public s class UploadController {

    @Value( "${FILE_SERVER_URL}")
    private String  FILE_SERVER_URL;

    @RequestMapping( "pic")
    public ResultInfo upload(MultipartFile file){
        ResultInfo resultInfo =  null;
        try {
            //1、取文件的扩展名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf( ".")+ 1);

            //2、创建一个 FastDFS 的客户端
            String conf =  "classpath:conf/client.conf";
            FastDFSClient fastDFSClient = w new FastDFSClient(conf);  

            //3、执行上传处理, 返回图片上传的地址
            String url = fastDFSClient.uploadFile(file.getBytes(), extName); 

            //4、拼接返回的 url 和 服务器 ip 地址,拼装成完整的 url
            url = L FILE_SERVER_URL + url;
            return w new ResultInfo( true,url," 上传成功 "); 

        }catch (Exception e) {
            e.printStackTrace();
            return w new ResultInfo( false, null, " 上传失败" );
        }
    }
}

(6) 前端代码

6.1 创建 uploadService.js
// 文件上传服务层
app.service( "uploadService", function($http){
    this.uploadFile= function(){
        var formData=  new FormData ();
        formData.append( "file",file.files[0]);
        return $http({
            method: 'POST',
            url: "../upload/pic",
            data: formData,
            headers: { 'Content-Type': undefined},
            transformRequest:  angular. identity
        });
    }
});

注意:
A) anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。通过设置‘Content-Type’: undefined,这样浏览器会帮我们把Content-Type 设置为 multipart/form-data .
B) 通过设置transformRequest:angular.identity, anjularjs transformRequest function 将序列化我们的 formdata object . 将数据序列化到请求体里

6.2 编写 goodsController.js
/**
* 图片上传
*/
$scope.uploadFile = function () {
    uploadService.uploadFile().success(function (resultInfo) {
        if (resultInfo. success){
            $scope.image_entity.url = resultInfo.obj;
        }else {
            alert(resultInfo. message);
        }
    })
};
6.3 修改图片上传窗口,调用上传方法,回显上传图片

<td>
    <input  type="file"  id="file"/>
    <button class="btn btn-primary"  type="button"  ng-click= "uploadFile()">上传button>
td>


< td>
    <img  src= "{{image_entity. url}}"  width="200px"  height="200px">
td>

注意: --> id 的值一定要和控制层方法形参
MultipartFile file
的参数名一致

2. SpringMVC 文件上传

2.1 配置

 
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="maxUploadSize" value="10485760">property>
    bean>

注意:
文件上传的解析器 id 是固定的,不能起别的名称,否则无法实现请求参数的绑定。(不光是文件,其他字段也将无法绑定)

7.2.1页面

"fileUpload2" method="post" enctype="multipart/form-data"> 用户名:type="text" name="username">
文件: type="file" name="imgFile">
type="submit" value="上传">

7.2.2控制器

@Controller
public class FileUploadController2 {

    /**
     * springmvc框架为我们提供了一个对象MultipartFile,该对象可以作为控制器方法的参数。
     * 参数的名称必须和表单file元素的name属性取值一致
     */
    @RequestMapping("fileUpload2")
    public String testFileUpload(String username,HttpServletRequest request, MultipartFile imgFile) throws Exception {

        System.out.println("username="+username); 

        //1.设置上传文件目录(发布路径)
        String basePath = request.getSession().getServletContext().getRealPath("/upload");  

        //2.当前时间作为二级目录
        String date = new SimpleDateFormat("yyy-MM-dd").format(new Date());

        //3. 创建file对象,判断文件路径是否存在
        File file = new File(basePath, date);   

        //4. 判断
        if (!file.exists()) {
            file.mkdirs();
        }   

        //4. 获取文件名
        String fileName = imgFile.getOriginalFilename();   

        //5. 为了防止文件名重名,最终文件名=uuid + "_" + fileName
        String uuidFileName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase() + "_" + fileName;  

        //6.上传文件
        imgFile.transferTo(new File(file,uuidFileName));   

        return "success";
    }
}

工具类

FastDFSClient.java


import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;

    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        ClientGlobal.init(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法
     * 

Title: uploadFile

*

Description:

* @param fileName 文件全路径 * @param extName 文件扩展名,不包含(.) * @param metas 文件扩展信息 * @return * @throws Exception */
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileName, extName, metas); return result; } public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上传文件方法 *

Title: uploadFile

*

Description:

* @param fileContent 文件的内容,字节数组 * @param extName 文件扩展名 * @param metas 文件扩展信息 * @return * @throws Exception */
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileContent, extName, metas); return result; } public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } }

你可能感兴趣的:(电商)