欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot上傳文件并返回url過程

 更新時間:2022年11月17日 08:36:06   作者:明明joy  
這篇文章主要介紹了springboot上傳文件并返回url過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

springboot上傳文件并返回url

1.首先在yml中配置文件上傳地址 

2.文件保存本地沒有配置在服務(wù)器上 需要多寫一個api,在上傳的最后生成一個url

直接上代碼

@Slf4j
@Service
public class StuEmailPhotoServiceImpl implements StuEmailPhotoService {
 
    @Value("${file.email_img_url}")
    String imageUrl;
    @Value("${img.url}")
    String imgUrl;
    @Resource
    StuEmailPhotoMapper stuEmailPhotoMapper;
 
    /**
     * 郵件上傳圖片
     *
     * @param classId
     * @param file
     * @param request
     * @return
     */
    @Override
    public ResultImg batchUpload(Long classId, MultipartFile file, HttpServletRequest request) {
 
        if (null == file) {
            return new ResultImg(ResultInfo.FAIL_CODE, "傳入文件為空!");
        }
        String errMsg = null;
        String newName = null;
        try {
            String oldName = file.getOriginalFilename().toLowerCase();  //獲取圖片的名稱
            String imgPath = null;
            newName = classId + "-emailTemplate-" + UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
            imgPath = imageUrl + classId; // + "/" + newName
            File folder = new File(imgPath);
            //沒有文件夾就創(chuàng)建
            if (!folder.exists()) {
                folder.mkdirs();
            }
 
            //壓縮圖片再保存outputQuality(1f) 越接近1,圖片質(zhì)量越高
            String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(1f).outputFormat(suffix).toFile(new File(folder, newName));
 
            //存儲圖片信息
            StuEmailPhoto stuEmailPhoto = new StuEmailPhoto();
            stuEmailPhoto.setClassId(classId);
            stuEmailPhoto.setImgOname(oldName);
            stuEmailPhoto.setImgName(newName);
            stuEmailPhoto.setImgUrl(imgPath + "/" + newName);
            stuEmailPhoto.setCreateTime(DateFormatUtils.getCurrentTime());
            stuEmailPhoto.setCreator(SecurityUtils.getCurrentUserId());
            stuEmailPhotoMapper.insert(stuEmailPhoto);
 
        } catch (Exception e) {
            errMsg = e.getLocalizedMessage();
            log.error("------StuPlatTrans--------batchUpload-----------:" + e);
        }
        if (StringUtils.isNotEmpty(errMsg)) {
            return new ResultImg(ResultInfo.FAIL_CODE, errMsg);
        }
 
        String url = imgUrl + "api/selectData/readImageView/emailTemplate/" + classId + "/" + newName;
        ImgUrl imgUrl = new ImgUrl();
        imgUrl.setUrl(url);
        List<ImgUrl> urlList = new ArrayList();
        urlList.add(imgUrl);
        return new ResultImg(0, urlList);
    }
 
    /**
     * 瀏覽器讀取圖片
     *
     * @param classId
     * @param imgName
     * @param request
     * @param response
     */
    @Override
    public void readImageView(Long classId, String imgName, HttpServletRequest request, HttpServletResponse response) {
        log.info("----------調(diào)用郵箱readImageView方法---------------");
 
        ServletOutputStream outputStream = null;
        FileInputStream inputStream = null;
 
        try {
            //獲取圖片存放路徑
            String imgPath = null;
            StuEmailPhoto stuEmailPhoto = stuEmailPhotoMapper.getUrlByNameAndClassId(classId, imgName);
            imgName = stuEmailPhoto.getImgName();
            String suffix = imgName.substring(imgName.lastIndexOf(".") + 1);
//            StuPlatTransfer transfer = transferMapper.getImageUrlByName(java.net.URLDecoder.decode(imgName, "utf-8") );
            log.info(JsonHelper.toJsonString(stuEmailPhoto));
            imgPath = stuEmailPhoto.getImgUrl();
            if (null != imgPath) {
                File imgFile = new File(imgPath);
                if (!imgFile.exists()) {
                    return;
                }
//                response.setContentType("application/octet-stream; charset=utf-8");
                response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
                response.addHeader("Access-Control-Expose-Headers", "token,uid,Content-Disposition");
                response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
                response.addHeader("Access-Control-Allow-Headers", "Content-Type");
                response.addHeader("Access-Control-Allow-Credentials", "true");
                response.addHeader("Content-Length", "" + imgFile.length());
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
 
                inputStream = new FileInputStream(imgFile);
                response.setContentType("image/" + suffix + ";charset=utf-8");
                outputStream = response.getOutputStream();
                //讀取文件流
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            }
 
        } catch (Exception e) {
            log.error("-----readImageView---imageName--" + imgName + "--err:" + e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("-----readImageView---input close--" + imgName + "--e:" + e);
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("-----readImageView---out close--" + imgName + "--e:" + e);
            }
        }
    }
}

springboot上傳文件兩種方式

1.文件保存在服務(wù)器,url地址保存在數(shù)據(jù)庫

	/**
	 * 1.文件保存在服務(wù)器,url地址保存在數(shù)據(jù)庫
     * 上傳成功之后返回成功保存的url地址
     */
@PostMapping("/upload")
    public @ResponseBody String upload(@RequestParam MultipartFile file, HttpServletRequest request){
        if(!file.isEmpty()){
            String uploadPath = "C:\uploadFile";
            // 如果目錄不存在則創(chuàng)建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//獲取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//獲取文件后綴名
            //重新隨機生成名字
            String filename = UUID.randomUUID().toString() +suffixName;
            File localFile = new File(uploadPath+"\"+filename);
            try {
                file.transferTo(localFile); //把上傳的文件保存至本地
                /**
                 * 這里應(yīng)該把filename保存到數(shù)據(jù)庫,供前端訪問時使用
                 */
                return filename;//上傳成功,返回保存的文件地址
            }catch (IOException e){
                e.printStackTrace();
                System.out.println("上傳失敗");
                return "";
            }
        }else{
            System.out.println("文件為空");
            return "";
        }
    }

2.直接把文件以二進制形式保存到數(shù)據(jù)庫中數(shù)據(jù)類型為blob的一個字段

/**
*上傳圖片,使用mybatis-plus保存到數(shù)據(jù)庫
*User為實體類,數(shù)據(jù)庫對應(yīng)user表,有id、image兩個屬性
*/
@PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws Exception{
        if(!file.isEmpty()){
            User user=new User();
            user.setImage(file.getBytes());
            userMapper.insert(user);
        }
        return "ok";
    }
/**
*前端通過id獲取數(shù)據(jù)庫中的圖片
*/
    @GetMapping("/getImage")
    @ResponseBody
    public void getImage(String id,HttpServletResponse resp) throws Exception{
        User user=userMapper.selectById(id);
        byte[] image = (byte[])user.getImage();
        resp.setContentType("image/jpeg");
        ServletOutputStream out = resp.getOutputStream();
        out.write(image);
        out.flush();
        out.close();
    }

3.前端代碼

<form action="/upload" method="post" enctype="multipart/form-data">
? ? <input type="file" name="file" /><br/>
? ? <input type="submit" name="" id="" value="提交" />
</form>

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • mybatis動態(tài)新增(insert)和修改(update)方式

    mybatis動態(tài)新增(insert)和修改(update)方式

    這篇文章主要介紹了mybatis動態(tài)新增(insert)和修改(update)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • SpringMvc請求處理參數(shù)?和?響應(yīng)數(shù)據(jù)處理的示例詳解

    SpringMvc請求處理參數(shù)?和?響應(yīng)數(shù)據(jù)處理的示例詳解

    這篇文章主要介紹了SpringMvc請求處理參數(shù)和響應(yīng)數(shù)據(jù)處理,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • Java 實現(xiàn)棧的三種方式

    Java 實現(xiàn)棧的三種方式

    這篇文章主要介紹了棧:LIFO(后進先出),自己實現(xiàn)一個棧,要求這個棧具有push()、pop()(返回棧頂元素并出棧)、peek() (返回棧頂元素不出棧)、isEmpty()這些基本的方法,需要的朋友可以參考下
    2020-12-12
  • java hashtable實現(xiàn)代碼

    java hashtable實現(xiàn)代碼

    這篇文章介紹了java hashtable實現(xiàn)代碼,有需要的朋友可以參考一下
    2013-10-10
  • JAVA實現(xiàn)LRU算法的參考示例

    JAVA實現(xiàn)LRU算法的參考示例

    這篇文章主要介紹了JAVA實現(xiàn)LRU算法的參考示例,幫助大家根據(jù)需求實現(xiàn)算法,感興趣的朋友可以了解下
    2020-10-10
  • Java如何實現(xiàn)Unicode和中文相互轉(zhuǎn)換

    Java如何實現(xiàn)Unicode和中文相互轉(zhuǎn)換

    這篇文章主要介紹了Java如何實現(xiàn)Unicode和中文相互轉(zhuǎn)換問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 詳解Spring中BeanUtils工具類的使用

    詳解Spring中BeanUtils工具類的使用

    這篇文章主要通過一些示例為大家詳細介紹了Spring中BeanUtils工具類的使用,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下
    2022-06-06
  • springboot整合webservice使用簡單案例總結(jié)

    springboot整合webservice使用簡單案例總結(jié)

    WebService是一個SOA(面向服務(wù)的編程)的架構(gòu),它是不依賴于語言,平臺等,可以實現(xiàn)不同的語言間的相互調(diào)用,下面這篇文章主要給大家介紹了關(guān)于springboot整合webservice使用的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • Spring Validation方法實現(xiàn)原理分析

    Spring Validation方法實現(xiàn)原理分析

    這篇文章主要介紹了Spring Validation實現(xiàn)原理分析,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Java中的注解、元注解詳細解析

    Java中的注解、元注解詳細解析

    這篇文章主要介紹了Java中的注解、元注解詳細解析,注解也叫元數(shù)據(jù),與類、接口、枚舉是在同一個層次,它可以聲明在包、類、字段、方法、局部變量、方法參數(shù)等的前面,用來對這些元素進行說明,注釋,需要的朋友可以參考下
    2023-11-11

最新評論