java 图片上传

前端#

<div>
    <form method="post" action="/upload/file" enctype="multipart/form-data">

        <input type="file" name="file" ><br/>

        <input type="submit" value="提交">

    </form>

</div>

后台

上传

  /**
     * 单文件上传
     * @return
     */
    @RequestMapping("/file")
    @ResponseBody
    public String upoadFile(@RequestParam("file")MultipartFile file) throws FileNotFoundException {
        if (file.isEmpty()){
            return "文件为空 上传失败";
        }
        // 获取上传文件的名字
        String fileName = file.getOriginalFilename();
        /**
         * 获取spring boot 的项目相对路劲
         */
        String path = System.getProperty("user.dir");
        /**
         * img 后面要加上/ 否则就不能传到这个目录
         */
        path+="/src/main/resources/static/img/";
        File dest = new File(path+fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

下载

 @RequestMapping("/download")
    public String  download(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        String path = System.getProperty("user.dir");
        path+="/src/main/resources/static/img/";
        // path 指要下载文件的路劲
        File dest = new File(path);
       File[] files = dest.listFiles();
        System.out.println(files.length);
         String name = files[0].getName();
         if (name != null){
          File file = new File(path,name);
          // 如果文件存在 开始下载
          if (file.exists()){
              // 配置文件下载
              response.setHeader("content-type", "application/octet-stream");
              response.setContentType("application/octet-stream");
              // 下载文件能正常显示中文
              response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
              // 实现文件下载
              byte[] buffer = new byte[1024];
              FileInputStream fis = null;
              BufferedInputStream bis = null;
              try {
                  fis = new FileInputStream(file);
                  bis = new BufferedInputStream(fis);
                  OutputStream os = response.getOutputStream();
                  int i = bis.read(buffer);
                  while (i != -1) {
                      os.write(buffer, 0, i);
                      i = bis.read(buffer);
                  }
                  System.out.println("Download the song successfully!");
              }
              catch (Exception e) {
                  System.out.println("Download the song failed!");
              }finally {
                  if (bis != null) {
                      try {
                          bis.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
                  if (fis != null) {
                      try {
                          fis.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
         }
         return null;

    }

fastdfs 上传图片

配置

#单个文件最大尺寸(设置100)
spring.servlet.multipart.max-file-size=100MB
#一个请求文件的最大尺寸
spring.servlet.multipart.max-request-size=100MB
#设置一个文件上传的临时文件目录(本地需要创建个目录)
spring.servlet.multipart.location=D:/opt/temp/

#FastDfs的配置	====================================
#读取inputsream阻塞时间
fdfs.connect-timeout=600
fdfs.so-timeout=1500
#tracker地址
fdfs.trackerList=192.168.182.135:22122 
#缩略图配置
#fdfs.thumbImage.height=150
#fdfs.thumbImage.width=150
#spring.jmx.enabled=false
#通过nginx 访问地址
fdfs.resHost=192.168.182.135
fdfs.storagePort=8888
#获取连接池最大数量
fdfs.pool.max-total=200 
**FdfsConfig主要用以连接fastdfs**
@Component
public class FdfsConfig {

    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.storagePort}")
    private String storagePort;

    public String getResHost() {
        return resHost;
    }

    public void setResHost(String resHost) {
        this.resHost = resHost;
    }

    public String getStoragePort() {
        return storagePort;
    }

    public void setStoragePort(String storagePort) {
        this.storagePort = storagePort;
    }
}



FdfsConfiguration使配置生效

@Configuration
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfiguration {
}

@Import(FdfsClientConfig.class) 在启动类上添加注解

上传工具类

@Component
public class CommonFileUtil {

    @Autowired
    private FastFileStorageClient storageClient;


    /**
     *	MultipartFile类型的文件上传ַ
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     * 普通的文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        StorePath path = storageClient.uploadFile(inputStream, file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return getResAccessUrl(path);
    }

    /**
     * 带输入流形式的文件上传
     *
     * @param is
     * @param size
     * @param fileName
     * @return
     */
    public String uploadFileStream(InputStream is, long size, String fileName) {
        StorePath path = storageClient.uploadFile(is, size, fileName, null);
        return getResAccessUrl(path);
    }

    /**
     * 将一段文本文件写到fastdfs的服务器上
     *
     * @param content
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath path = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(path);
    }

    /**
     * 返回文件上传成功后的地址名称ַ
     * @param storePath
     * @return
     */
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     * @param fileUrl
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {

        }
    }

    public String upfileImage(InputStream is, long size, String fileExtName, Set<MateData> metaData) {
        StorePath path = storageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData);
        return getResAccessUrl(path);
    }





}

controller

fileUtil 是工具 直接注入就可以

    //使用fastdfs进行文件上传
    @RequestMapping("/uploadFileToFast")
    public String uoloadFileToFast(@RequestParam("file")MultipartFile file) throws IOException{

        if(file.isEmpty()){
           return "文件不存在";
        }
        String path = fileUtil.uploadFile(file);
        System.out.println(path);
        return "上传成功";
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值