Добавление изображения в SQl таблицу

148
29 ноября 2018, 22:20

Создаю Форум с добавлением текста и изображения.Вот уже который день не могу загрузить изображение в таблицу данных.Прощу помочь.В этой сфере новичок)А есть ли более улучшенный вид для хостинга изображения?

@Controller
public class PostController {

    @Autowired
    CategoryService service;
    @Autowired
    UsersService usersService;
    @Autowired
    SubCategoryService subcategory;
    @Autowired
    PostService postService;

    private Date getDate() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime();
    }

    @GetMapping("/post")
    public ModelAndView gotoPost(Principal principal) {
        String user = principal.getName();
        ModelAndView model = new ModelAndView("post");
        List<CategoryEntity> cate = service.getAllCategorys();
        List<Subcategory> cate2 = subcategory.getAllSubcategory();
        model.addObject("user", usersService.getUsersByUsername(user));
        model.addObject("category", cate);
        model.addObject("subcat", cate2);
        return model;
    }
    @PostMapping("/post")
    public ModelAndView postNewPost
            (HttpServletRequest request, @RequestParam("myImage") MultipartFile file) throws IOException {
        PostEntity entity = new PostEntity();
        ModelAndView model = new ModelAndView("post");
        int userId = Integer.parseInt(request.getParameter("userId"));
        int categoryId = Integer.parseInt(request.getParameter("txtCategory"));
        int subCategoryId = Integer.parseInt(request.getParameter("txtSubCategory"));
        entity.setUserId(userId);
        entity.setCategoryId(categoryId);
        entity.setSubcategoryId(subCategoryId);
        if (file != null) {
                System.out.println("Saving file:   " + file.getOriginalFilename());
                entity.setLogo(file.getOriginalFilename());
                entity.setFileData(file.getBytes());

                entity.setText(request.getParameter("Text"));
                entity.setDate(getDate());
                postService.savePost(entity);
                model.addObject("message", "succes");
                model.setViewName("post");

        } else {
            model.setViewName("401");
        }
        return model;
    }
}

это html

<div class="container">
    <h1 th:text="${message}"></h1>
    <h2>Form control: textarea</h2>
    <p>The form below contains a textarea for comments:</p>
    <form th:action="@{/post}" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="userId" th:value="${user.id}"></input>
        <div class="form-group" >
            <label for="FormControlSelect1">Category</label>
            <select class="form-control" id="FormControlSelect1" name="txtCategory">
                <option th:each="cate:${category}" th:text="${cate.categoryName}" th:value="${cate.id}" ></option>
            </select>
        </div>
        <div class="form-group">
            <label for="FormControlSelect2">Subcategory</label>
            <select class="form-control" id="FormControlSelect2" name="txtSubCategory">
                <option th:each="subcategory:${subcat}" th:text="${subcategory.subCateName}" th:value="${subcategory.id}"></option>
            </select>
        </div>
        <div class="custom-file">
            <input type="file" class="custom-file-input" id="customFile" name="myImage">
            <label class="custom-file-label" for="customFile">Choose image file...</label>
        </div>
        <div class="form-group">
            <label for="comment">Comment:</label>
            <textarea class="form-control" name="Text" rows="5"  id="comment"></textarea>
        </div>
        <input type="submit" id="button" class="btn btn-danger right" value="Gonder">
    </form>
</div>

Выводится ошибка

Incorrect string value: '\xFF\xD8\xFF\xE1&\xD9...' for column 'file_data' at row 1

Answer 1

создайте файл в диске D:// а в mysql нужно хранить просто path фотографии вот пример это из моего проекта поменяйте параметры по вашему во первых в application.properties объявим место папки который мы создали в диске D:/ чтобы объявить напишем этот строка в application.properties

springBlog.user.pic.url=D:\\имя папки\\

потом в контроллере объявим переменный по типу String и дадим value на эту строку это выглядит вот так

@Value("${springBlog.user.pic.url}")
private String examplePicture;

потом у нас есть метод для добавлении фотографии вот

    @PostMapping(value = "/addPicture")
public String addArticle(@ModelAttribute("Имя вашего модела") Model model, @RequestParam("pict") MultipartFile multipartFile) throws IOException {
    File dir = new File(examplePicture);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    String picName = System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename();
    multipartFile.transferTo(new File(dir, picName));
    model.setImage(picName);
    ModelRepository.save(model);
    return "redirect:/";
}

потом в html создадим форма

<form action="#" th:action="@{/addPicture}" th:object="${***}" method="post" enctype="multipart/form-data" >
    <input type="file" name="pict">-здесь дадим параметр который мы дали в методе
    <input type="submit" value="add">
</form>
Answer 2

Вариант 1 (Не самый лучший) Конвертировать файл в строку Base64 и сохранить в базу.

//Конвертируем байты з файла в строку Base64
byte [] byteArr=file.getBytes();
String encodedString = Base64.getEncoder().encodeToString(byteArr);
//Конвертируем строку назад в байты
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);

Вариант 2 1. Добавляем глобальную переменную.

@Autowired
private HttpServletRequest servletRequest;
  1. Получаем реальный путь на сервере, создаем файл и копируем наш MultipartFile в созданий файл

    String uploadsDir = "/uploads/";
    String realPathtoUploads =  
            request.getSession().getServletContext().getRealPath(uploadsDir);
    if(! new File(realPathtoUploads).exists()) {
         new File(realPathtoUploads).mkdir();
    }
    String orgName = file.getOriginalFilename();
    String filePath = realPathtoUploads + orgName;
    File dest = new File(filePath);
    file.transferTo(dest);
    
READ ALSO
Как задать класс элементу списка при клике?

Как задать класс элементу списка при клике?

Есть такой компонент, который отвечает за динамическое отображение спискаКак при клике задать активный класс элементу, по которому кликнули

157
TypeError: $.browser is undefined

TypeError: $.browser is undefined

Хочу сделать переход якорю плавнымВот html:

156
По поисковым запросам и релевантности [закрыт]

По поисковым запросам и релевантности [закрыт]

Я ввожу Jahonts в поиск по латвии и мне выводит столбец с отделами сайта, адресом ,верменем работы и телефономKак добится того же на своём сайте...

104
Вывод input name AJAX

Вывод input name AJAX

Нужно вывести в тег заполненное имя форма:

208