发表于: 2019-10-13 19:12:10

1 883


一、今天完成的事
1.修改程序,从后端传到的但是出现了问题
再使用spring来管理accessKey
ImageController
package com.ksy.controller;
import com.ksy.uploadUtil.ImageUtil;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServlet;
import java.io.File;
/**
* @author shiyang
* @PackageName com.ksy.controller
* @ClassName ksy
* @Description
* @create 2019-10-13 18:05
*/
@Controller
public class ImageController {
    @Autowired
    ImageUtil imageUtil;
    private static final Logger log = LogManager.getLogger(ImageController.class);
    @RequestMapping(value = "/a/image", method = RequestMethod.POST)
    public String imageUpload(MultipartFile multipartFile) throws Exception{
        // 上传图片
        log.info(multipartFile);
        CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        boolean state = imageUtil.uploadImage((MultipartFile) file);
        log.info("图片上传状态=====" + state);
        return "url";
    }
}
spring
<bean id="imageUtil" class="com.ksy.uploadUtil.ImageUtil">
    <constructor-arg name="endpoint" value="http://oss-cn-beijing.aliyuncs.com"/>
    <constructor-arg name="accessKeyId" value="LTAI4Fqn*******Sdh8m8198"/>
    <constructor-arg name="accessKeySecret" value="4MEO5ked********djAm3Po2d6"/>
    <constructor-arg name="bucketName" value="keshiyang"/>
</bean>
imageUtil
package com.ksy.uploadUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.google.gson.Gson;
import com.sun.deploy.config.ClientConfig;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author shiyang
* @PackageName com.ksy.uploadUtil
* @ClassName ksy
* @Description
* @create 2019-09-29 16:33
*/
public class ImageUtil extends HttpServlet {
    public String endpoint;
    public String accessKeyId;
    public String accessKeySecret;
    public String bucketName;
    public ImageUtil(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
    }
    public boolean uploadImage(MultipartFile file) throws IOException {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String key = System.currentTimeMillis() + file.getOriginalFilename();
        // 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
        ossClient.putObject(bucketName, key, new ByteArrayInputStream(file.getBytes()));
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }
}
jsp,这里上传的时候出现了一个不知道是不是坑的报错。这里的name和后端获取的name要一致,不然要报错
<form id="logoForm" enctype="multipart/form-data" action="${pageContext.request.contextPath}/a/image" method="post">
    <label for="multipartFile" class="input-tips2">图片:</label>
    <div class="inputOuter2" style="text-align: center">
        <input type="file" id="multipartFile" name="multipartFile" maxlength="10"
               class="inputstyle2"/>
        <input type="submit" value="上传">
    </div>
</form>
程序报错

报错信息为java.io不能转换为 multipart类型
百度上说是包没有导进去,查看pom
<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
是导进去的
还是没有修改成功

二、遇到的问题
三、收获
csdn上看到一篇关于multipartFile转换的文章,明天按照这个来修改
什么是MultipartFile
MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。【来自百度知道】

MultipartFile 与 File 的 互相转换
1. File转MultipartFile
(1):使用org.springframework.mock.web.MockMultipartFile 需要导入spring-test.jar
public static void main(String[] args) throws Exception {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        // MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
        // 其中originalFilename,String contentType 旧名字,类型  可为空
        // ContentType.APPLICATION_OCTET_STREAM.toString() 需要使用HttpClient的包
        MultipartFile multipartFile = new MockMultipartFile("copy"+file.getName(),file.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
        System.out.println(multipartFile.getName()); // 输出copytest.txt
    }

(2):使用CommonsMultipartFile
public static void main(String[] args) throws Exception {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        // 需要导入commons-fileupload的包
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
           while ( (n = inputStream.read(buffer,0,4096)) != -1){
               os.write(buffer,0,n);
           }
            //也可以用IOUtils.copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
2. MultipartFile转File
(1):使用File转MultipartFile的逆过程
你在看这个代码的时候会觉得很熟悉,是的这个就是File转MultipartFile的逆转过程,这个方法会在根目录生成一个文件,需要删除该文件。

public static void main(String[] args) throws Exception {
        int n;
        // 得到MultipartFile文件
        MultipartFile multipartFile = getFile();
        File f = null;
        // 输出文件的新name 就是指上传后的文件名称
        System.out.println("getName:"+multipartFile.getName());
        // 输出源文件名称 就是指上传前的文件名称
        System.out.println("Oriname:"+multipartFile.getOriginalFilename());
        // 创建文件
        f = new File(multipartFile.getOriginalFilename());
        try ( InputStream in  = multipartFile.getInputStream(); OutputStream os = new FileOutputStream(f)){
            // 得到文件流。以文件流的方式输出到新文件
            // 可以使用byte[] ss = multipartFile.getBytes();代替while
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            // 读取文件第一行
            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
            System.out.println(bufferedReader.readLine());
            // 输出路径
            bufferedReader.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        // 输出file的URL
        System.out.println(f.toURI().toURL().toString());
        // 输出文件的绝对路径
        System.out.println(f.getAbsolutePath());
        // 操作完上的文件 需要删除在根目录下生成的文件
        File file = new File(f.toURI());
        if (file.delete()){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
    /**
     *
     * @Description 返回MultipartFile文件
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //也可以用IOUtils.copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

(2):使用transferTo (本质上还是使用了流 只不过是封装了步骤)
会生成文件,最后不需要文件要删除

public static void main(String[] args) throws Exception {
        String path = "F:\\demo\\";
        File file = new File(path,"demo.txt");
        // 得到MultipartFile文件
        MultipartFile multipartFile = getFile();
        /*byte[] ss = multipartFile.getBytes();
        OutputStream os = new FileOutputStream(file);
        os.write(ss);
        os.close();*/
        multipartFile.transferTo(file);
        // 读取文件第一行
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        System.out.println(bufferedReader.readLine());
        // 输出绝对路径
        System.out.println(file.getAbsolutePath());
        bufferedReader.close();
        // 操作完上的文件 需要删除在根目录下生成的文件
        if (file.delete()){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
    /**
     *
     * @Description 返回MultipartFile文件
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //也可以用IOUtils.copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

(3):使用FileUtils.copyInputStreamToFile()
也是会生成文件,到最后也是要删除文件
public static void main(String[] args) throws Exception {
        String path = "F:\\demo\\";
        File file = new File(path,"demo.txt");
        // 得到MultipartFile文件
        MultipartFile multipartFile = getFile();
        // 把流输出到文件
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
        // 读取文件第一行
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        System.out.println(bufferedReader.readLine());
        // 输出绝对路径
        System.out.println(file.getAbsolutePath());
        bufferedReader.close();
        // 操作完上的文件 需要删除在根目录下生成的文件
        if (file.delete()){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
    /**
     *
     * @Description 返回MultipartFile文件
     * @return org.springframework.web.multipart.MultipartFile
     * @date 2019/1/5 11:08
     * @auther dell
     */
    public static MultipartFile getFile() throws IOException {
        String filePath = "F:\\test.txt";
        File file = new File(filePath);
        FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
            while ( (n = inputStream.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            //也可以用IOUtils.copy(inputStream,os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            System.out.println(multipartFile.getName());
            return multipartFile;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

4:强转类型
CommonsMultipartFile commonsmultipartfile = (CommonsMultipartFile) multipartFile;
DiskFileItem diskFileItem = (DiskFileItem) commonsmultipartfile.getFileItem();
File file = diskFileItem.getStoreLocation();
这种强转你获得的file只是一个空壳

你能获取的也只有这个F:\upload_edfce39f_2894_4b66_b865_d5fb8636bdf3_00000000.tmp 网上有说会在根目录生成临时文件的,从tmp也可以看出来是个临时文件,但是我试了好几次啥都没找到。。。。直接获取这个file读取内容也是会报文件找不到的 这是必然的 当然也有在spring配置文件配置CommonsMultipartResolver的 这就感觉很麻烦了。。。。
但是我们可以看一下diskFileItem 看下图 是不是很熟悉了,从diskFileItem可以获取文件流,其实你看了源码你就知道获取文件流都是从这里获取的。剩下的就好办了 我就不赘述了/。

在使用临时文件的时候可以使用缓冲区创建临时文件
//  createTempFile(String prefix, String suffix)
//  prefix 文件名 suffix 文件格式
// 默认是tmp格式  C:\Users\dell\AppData\Local\Temp\tmp8784723057512789016.tmp
File file =File.createTempFile("tmp", null);
// txt格式  C:\Users\dell\AppData\Local\Temp\tmp2888293586594052933.txt
File file =File.createTempFile("tmp", ".txt");

HttpClient构建上传文件参数并实现中转文件
这里不自己给例子了,参考了其他博客的代码

// 获取文件名称
String fileName = file.getOriginalFilename();
HttpPost httpPost = new HttpPost(url);
// 创建文件上传实体
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
builder.addTextBody("filename", fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交

执行提交之后你会发现你上传的文件名会出现中文乱码
这里参考
HttpClient上传文件中文名乱码 该博客详细说明了为什么会乱码以及怎么解决
我使用的解决办法是:

//设置模式为RFC6532
builder.setMode(HttpMultipartMode.RFC6532);



四、明天的计划



返回列表 返回列表
评论

    分享到