在Spring中上传文件

时间:2015-04-20 09:05:00

标签: spring multipart

我正在尝试使用服务器上的以下代码上传音频文件。现在,它非常适用于图像文件但不适用于音频。我认为MultipartFile也可以用于音频文件。任何人都可以告诉我什么这里错了吗? 我收到“服务器拒绝了这个请求,因为请求实体的格式不受所请求方法所请求资源的支持。”错误。

MultipartFile不能用于音频文件吗?如果没有替代方案吗?

@Transactional
public BaseVO uploadImage(MultipartFile file, long userId){
    Map<String, Object> alertParams = new HashMap<String, Object>();

    try{
        if (!file.isEmpty()) {
            Image profileImage = imageRepository.findByUserId(userId);
            if(profileImage == null){
                profileImage = new Image();
                profileImage.setUserId(userId);
            }

            File dir = null;
            String realPath;
            if(liveBuild == "true"){
                realPath = liveImageUploadRepository;
                dir = new File(realPath);
            }else{
                HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                realPath = request.getSession().getServletContext().getRealPath("/") + devImageUploadRepository;
                dir = new File(realPath);
            }
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String finalFileStorePath = realPath + "/" + userId + ".jpg";
            File path = new File(finalFileStorePath);
            file.transferTo(path);

            profileImage.setImagePath(realPath);
            //profileImage.setImageName(userId + ".jpg");
            profileImage.setImageName(userId+"");
            profileImage.setImageType(".jpg");

            imageRepository.save(profileImage);

            alertParams.put("id", profileImage.getId());
        } else {
            return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
        }
    }catch(HibernateException e){
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG + " " + e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
    } catch (IOException e) {
        e.printStackTrace();
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
    }
    return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}

0 个答案:

没有答案