用angularjs進行文件上傳

文件上傳頁面三要素:html

一、  form表單提交方式必定是posthtml5

二、  form表單的enctype必定是multipart/form-dataangularjs

三、  form表單中必定要有一個input的type是 fileweb

   文件上傳必定要有的jarspring

       Commons-io和commons-fileuploadjson

 Springmvc文件上傳:數組

一、  springmvc.xml中必定要有 多媒體解析器spring-mvc

  <bean id="multipartResolver"服務器

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">mvc

<property name="defaultEncoding" value="UTF-8"></property>

<!-- 設定文件上傳的最大值 5MB,5*1024*1024 -->

<property name="maxUploadSize" value="5242880"></property>

</bean>

二、  後臺Controller中的方法中形參使用MultipartFile類型接收文件,參數的名稱必定要和頁面上的參數名稱保持一致

 

本身編寫的上傳文件demo,上傳文件至FastDFS服務器,代碼以下:

package demo;

import org.csource.fastdfs.*;

public class FastfsDemo {
    public static void main(String[] args) throws Exception {
        ClientGlobal.init("G:\\pyg_parent\\pyg_shop_web\\src\\main\\resources\\fastdfs_client.conf");
//        二、建立一個 TrackerClient 對象。直接 new 一個
        TrackerClient trackerClient = new TrackerClient();
//        三、使用 TrackerClient 對象獲取鏈接,得到一個 TrackerServer 對象
        TrackerServer trackerServer = trackerClient.getConnection();
//        四、建立一個 StorageServer 的引用,值爲 null
        StorageServer storageServer = null;
//        五、建立一個 StorageClient 對象,須要兩個參數 TrackerServer 對象、StorageServer 的引用
        StorageClient storageClient = new StorageClient(trackerServer,storageServer);
//        六、使用 StorageClient 對象上傳圖片
        String[] strings = storageClient.upload_file("C:\\Users\\o_Osky\\Desktop\\1.png", "png", null);
//        七、返回數組。包含組名和圖片的路徑
        for (String string : strings) {
            System.out.println(string);
        }
//  storageClient.delete_file("group1", "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf")  刪除文件
} }

須要注意的是:上傳文件的路徑爲絕對路徑,在實際應用中,應用相對路徑,且demo中new 對象過多,因此封裝了工具類,代碼以下:

package utils;

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);
    }
    
    /**
     * 上傳文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @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);
    }
    
    /**
     * 上傳文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @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);
    }
}

配置spingmvc文件,配置解析器:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    <!--引用外部資源文件-->
    <context:property-placeholder location="classpath:config/application.properties"/>
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="application/json"/>
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteDateUseDateFormat</value>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--引用douub服務-->
    <dubbo:application name="pyg-shop-web"/>
    <dubbo:registry address="zookeeper://192.168.25.61:2181"/>
    <dubbo:annotation package="com.pyg.shop"/>
    <mvc:default-servlet-handler/>
    <!--配置多媒體解析器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 設定文件上傳的最大值 5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

</beans>

angularjsServer層代碼:

app.service("uploadService",function($http){
//    angularJS的文件上傳
    this.upload=function(){
//        html5的對象
        var formData = new FormData();
        formData.append("file",file.files[0]); //file.files[0] js的取值方式  取到頁面的第一個type=」file「  "file"與MultipartFile file 名字一致
        return $http({
            method:'post',
            url:'../upload/uploadFile',
            data:formData,
            headers: {'Content-Type':undefined},  //寫了這一行即聲明enctype類型必定是 multipart/form-data  
            transformRequest: angular.identity  //序列化上傳的文件
        });
    }
})

angularController層代碼:

  $scope.uploadFile = function () {
        uploadService.upload().success(function (result) {
            if (result.flag) {
                $scope.imgUrl = result.message;
            } else {
                alert(result.message);
            }
        })
    }

 

調用工具類實現文件上傳:

package com.pyg.shop.controller;

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


@RestController
@RequestMapping("/upload")
public class UploadController {
    /*
     * springmvc從properties中獲取變量的方式
     * application.properties==>upload_server=http://192.168.25.133/
     * */
    @Value("${upload_server}")
    private String uploadServer;

    @RequestMapping("/uploadFile")
    public ResultInfo uploadFile(MultipartFile file) {
        try {
            /*
            * tracker_server=192.168.25.133:22122
            * */
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fastdfs_client.conf");
            String fileName = file.getOriginalFilename();//獲取上傳文件的相對路徑
            /*
            * 獲取上傳文件的擴展名
            * png 不帶「.」 因此+1
            * */
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            /*
            * 文件上傳成功後,返回文件在服務器中位置
            * 爲了準確的url須要拼接上服務器ip,ip可能會變更,因此用配置文件加載服務器ip
            * */
            String fileUrl = fastDFSClient.uploadFile(file.getBytes(), extName);
            return new ResultInfo(true, uploadServer + fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo(false, "上傳失敗");
        }
    }
}

實現效果以下:

相關文章
相關標籤/搜索