package com.cxwlw.zhcs.controller.api;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URL;
import java.util.List;

@Controller
@RequestMapping("/api/file")
public class FileController {
@RequestMapping("/greeting")
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//文件上传相关代码
@RequestMapping(value="/upload")
@ResponseBody
public String upload(@RequestParam("test") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
String jarPath = this.getClass().getClassLoader().getResource("file").getPath();
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上传的后缀名为:" + suffixName);
// 文件上传后的路径
String filePath = "F://zhcs//src//main//resources//file//";
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// File dest = new File(jarPath +"//"+fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}

//文件下载相关代码
@RequestMapping("/download")
public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
String fileName = request.getParameter("name");
if (fileName != null) {
//当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
// String realPath = request.getServletContext().getRealPath(
// "//WEB-INF//file//");
String realPath ="F://zhcs//src//main//resources//file//";
// E://test// E:\\test\\经转换File file = new File(realPath, fileName);都是E:\test\
File file = new File(realPath, fileName);
if (file != null){
response.setContentType("image/jpeg");
FileInputStream is = null;
try {
is = new FileInputStream(file);
if (is != null){
try {
int i;
i = is.available();
byte data[] = new byte[i];
is.read(data); // 读数据
is.close();
response.setContentType("image/jpeg"); // 设置返回的文件类型
OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
toClient.write(data); // 输出数据
toClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 得到文件大小
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// if (file.exists()) {
// response.setContentType("application/force-download");// 设置强制下载不打开
// response.addHeader("Content-Disposition",
// "attachment;fileName=" + fileName);// 设置文件名
// 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("success");
// } catch (Exception e) {
// e.printStackTrace();
// } 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;
}
//多文件上传方法一 下载到该工程的所在目录下
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request)
.getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(file.getOriginalFilename())));
stream.write(bytes);
stream.close();

} catch (Exception e) {
stream = null;
return "You failed to upload " + i + " => "
+ e.getMessage();
}
} else {
return "You failed to upload " + i
+ " because the file was empty.";
}
}
return "upload successful";
}
//多文件上传方法二
@RequestMapping(value = "/batchupload", method = RequestMethod.POST)
@ResponseBody
public String batchFileUp(HttpServletRequest request)
{
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
//String contextPath = request.getSession().getServletContext().getRealPath("/")+ "\\uploadsTest";//可以将文件存放在这个目录下 是当前工程下的uploadtest目录下
// System.out.println(contextPath);
// File tempFile = new File(contextPath);
// if(!tempFile.exists())
// {
// tempFile.mkdir();
// }
for(int i=0 ;i<files.size();i++)
{
MultipartFile file = files.get(i);
System.out.println(file.getContentType());
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String fullfilePath = "E://test//" +fileName;//自己设定的文件目录
logger.info("fullfilePath:",fullfilePath);
if(!file.isEmpty())
{
try{
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File(fullfilePath)));
stream.write(file.getBytes());
stream.close();
}
catch (Exception e){
return "Failed to Upload"+fileName +"=>"+e.getMessage();
}
}
else
{
return "Failed to Upload "+ fileName +"because the file was empty";
}

}
return "Upload Success!";
}
}

greeting。html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="../static/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
function go(){
debugger;
var s=document.getElementById("id_user").value;
if(s==""){
alert("图片名称为空")
}else{
document.getElementById( "a").style.display= "block";
document.getElementById("aaa").href='/api/file/download?name='+s;
}
}
</script>
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/api/file/upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="test"/>
<input type="submit" />
</form>
图片名称:<input type="text" name="name_user" id="id_user"/>
<input type="button" onclick="go()" value="点击"/>
<div id="a" style="display:none;"><a id="aaa" href="" >下载test</a></div>
<!-- <p>多文件上传</p> -->
<!-- <form method="POST" enctype="multipart/form-data" action="/batch/upload"> -->
<!-- <p>文件1:<input type="file" name="file" /></p> -->
<!-- <p>文件2:<input type="file" name="file" /></p> -->
<!-- <p><input type="submit" value="上传" /></p> -->
<!-- </form> -->
<!-- <p>多文件上传1</p> -->
<!-- <form method="POST" enctype="multipart/form-data" action="/batchupload"> -->
<!-- <p>文件1:<input type="file" name="file" /></p> -->
<!-- <p>文件2:<input type="file" name="file" /></p> -->
<!-- <p><input type="submit" value="上传" /></p> -->
<!-- </form> -->
</body>
</html>

springboot 上传图片,地址,在页面展示图片的更多相关文章

  1. springboot+thymeleaf中前台页面展示中、将不同的数字替换成不同的字符串。使用条件运算符

    主要用到的知识就是thyme leaf中的条件运算符 表达式:(condition)?:then:else 当条件condition成立时返回then.否则返回else 具体代码:<td th: ...

  2. 手把手教小白如何用css+js实现页面中图片放大展示效果

    1.前言      很多童鞋会在项目中遇到一些上传图片,展示图片的操作,但是图片呢有大有小,为了页面的美观,有时候我们需要将图片展示成固定宽高度,但是呢,领导就会说,我想看大图片,怎么办?想看就看呀, ...

  3. 【SpringBoot】转载 springboot使用thymeleaf完成数据的页面展示

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/weixin_36380516/artic ...

  4. SpringBoot页面展示Thymeleaf

    https://www.jianshu.com/p/a842e5b5012e 开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了.Spring ...

  5. 【微信小程序云开发】1分钟学会实现上传、下载、预览、删除图片,并且以九宫格展示图片

    大家好,我叫小秃僧 这篇文章是讲解云开发如何上传.下载.预览.删除图片,并且以九宫格展示图片的功能 @ 目录 1. 实现效果 2.JavaScript代码 3.wxml代码 4.wxss代码 1. 实 ...

  6. app——分享wap站,数据处理页面展示

    无意中接到了一个小的工作任务:配合手机app端的分享功能做一个wap站,简言之:将手机app端分享的文章id传过来,利用此id再进行一系列的操作,由于文章分为纯文本,图文以及图集的三种类型的文章,因此 ...

  7. 【原】老生常谈-从输入url到页面展示到底发生了什么

    刚开始写这篇文章还是挺纠结的,因为网上搜索“从输入url到页面展示到底发生了什么”,你可以搜到一大堆的资料.而且面试这道题基本是必考题,二月份面试的时候,虽然知道这个过程发生了什么,不过当面试官一步步 ...

  8. 【转】老生常谈-从输入url到页面展示到底发生了什么

    今天看到了一篇很详细地解释了从输入url到页面展示过程的文章,好文章不能错过,所以转到自己这里来了. 原文地址:老生常谈-从输入url到页面展示到底发生了什么 以下为原文: 刚开始写这篇文章还是挺纠结 ...

  9. (转)老生常谈-从输入url到页面展示到底发生了什么

    刚开始写这篇文章还是挺纠结的,因为网上搜索"从输入url到页面展示到底发生了什么",你可以搜到一大堆的资料.而且面试这道题基本是必考题,二月份面试的时候,虽然知道这个过程发生了什么 ...

随机推荐

  1. 三种实现PHP伪静态页面的方法

    PHP伪静态写法--其一 伪静态又名:URL重写  主要是为了SEO而生的.(SEO是什么?这个不用问我吧.呵呵-搞网络的不懂SEO那就----) 方法一: 比如这个网页 /soft.php/1,10 ...

  2. 123457123456#0#-----com.yuming.HitMouse01--前拼后广--幼儿打地鼠游戏

    com.yuming.HitMouse01--前拼后广--幼儿打地鼠游戏

  3. Python - Django - 编辑作者

    在作者列表页面的操作栏中加上编辑按钮 <!DOCTYPE html> <html lang="en"> <head> <meta char ...

  4. curl 的用法指南

    简介 curl 是常用的命令行工具,用来请求 Web 服务器.它的名字就是客户端(client)的 URL 工具的意思. 它的功能非常强大,命令行参数多达几十种.如果熟练的话,完全可以取代 Postm ...

  5. DTCMS,添加文章时,内容中第一张图片作缩略图,并且等比例缩放图片

    DTCMS,添加文章时,内容中第一张图片作缩略图 admin/article/article_edit.aspx.cs 导入: using System.Drawing;using System.Dr ...

  6. 【C# 开发技巧】番外篇故事-我是一个线程

    我是一个线程 我是一个线程,一出生就被编了一个号——0x3704,然后被领到一间昏暗的屋子里,在这里,我发现了很多和我一模一样的同伴.我身边的同伴0x6900待的时间比较长,他带着沧桑的口气对我说:“ ...

  7. Unity与Android刘海屏适配

    本周学习Unity与Android刘海屏适配 关于刘海屏适配部分 网上有很多教程 这里只是做一下整理 https://blog.csdn.net/xj1009420846/article/detail ...

  8. 利用Python进行数据分析_Pandas_绘图和可视化_Matplotlib

    1 认识Figure和Subplot import matplotlib.pyplot as plt matplotlib的图像都位于Figure对象中 fg = plt.figure() 通过add ...

  9. 1233: 输出杨辉三角前n行(Java)

    WUSTOJ 1233: 输出杨辉三角前n行 题目 原题链接 Description 输出杨辉三角前n行. Input 输入一个数n(n <= 9) Output 输出杨辉三角前n行.(注意行末 ...

  10. gin PostForm 方法不起作用

    情景: 在httpie post 下,在 axios post下,总的来说,就是在form-data下只有c.Bind()会有用 如果一定要用c.PostForm() headers必须为x-www- ...